from a dictionary of dictionaries, return a list of the inner dictionaries, updated with the key

Viewed 51

Easier shown than explained.

This is what I have:

dict_of_dict = {'a': {'i': 1, 's': 'aa'}, 'b': {'i': 2, 's': 'bb'}}

This is what I want, i.e. I want add master dict's key to each inner dictionary and return them as a list.

[{'i': 1, 's': 'aa', 'key': 'a'}, {'i': 2, 's': 'bb', 'key': 'b'}]

Now, I already know how to do this without list comprehension.

li = []

for key, di in dict_of_dict.items():
    di.update(key=key)
    li.append(di)

I can also do it using a list comprehension to update the inner dicts with the keys. But I need a separate command to get the list of updated inner dictionaries.

[di.update(key=key) for key, di in dict_of_dict.items()]
li = list(dict_of_dict.values())

But I can't see how to do this in one pass with a list comprehension because dict.update() returns None, rather than the dict itself.

2 Answers
dict_of_dict = {'a': {'i': 1, 's': 'aa'}, 'b': {'i': 2, 's': 'bb'}}

out = [dict(**v, key=k) for k, v in dict_of_dict.items()]
print(out)

Prints:

[{'i': 1, 's': 'aa', 'key': 'a'}, {'i': 2, 's': 'bb', 'key': 'b'}]

Another solution using dict.update(), as asked in the question:

dict_of_dict = {'a': {'i': 1, 's': 'aa'}, 'b': {'i': 2, 's': 'bb'}}

d = [ {'key': key} for key in dict_of_dict ]

l = [ d[i] if d[i].update(ddd) is None else 0 for i,ddd in enumerate(list(dict_of_dict.values())) ]
print(l)
Related