Converting a dictionary of dictionaries to a List of dictionaries
Solution 1:
A list comprehension should do the job, no need for filter()
.
>>> dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}
>>> list_of_dics = [value for value in dic_of_dics.values()]
>>>list_of_dics
[{'a': 'A'}, {'b': 'B'}, {'c': 'C'}]
Solution 2:
Just to mention a solution with keeping first-level "key" associated with "id" inside next level of dictionaries.
to rephrase it "Converting a dictionary of dictionaries to a List of dictionaries with keeping key inside".
>>> dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}
>>> [(lambda d: d.update(id=key) or d)(val) for (key, val) in dic_of_dics.items()]
[{'a': 'A', 'id': 1}, {'b': 'B', 'id': 2}, {'c': 'C', 'id': 3}]
Solution 3:
I'm aware the question is somewhat old, but just in case someone needs the solution I was looking for:
If you want to keep the keys of the outer dict without having them as a value in the inner dict, the following code produces a list of tuples (key, dict)
for every inner dict.
>>> dic_of_dics = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}
>>> [(k,v) for k, v in dic_of_dics.items()]
[(1, {'a': 'A'}), (2, {'b': 'B'}), (3, {'c': 'C'})]
I used it to define a networkx
graph through the add_nodes_from()
function from a dict of dicts produced by the to_dict('index')
function from pandas
and it worked like a charm.