'Converting a dictionary of dictionaries to a List of dictionaries
I have a dictionary of dictionaries.Is there any possible way to convert it to a list of dictionaries? And if not, then how is the filter() method applied to filter data in a dictionary of dictionaries?
{"0": {"_ref": "ipam:stat/ZGkMTAuMTQ4LjEyLjAvMjIvMA:default/10.158.2.0/22",
"comment": "VLAN 0",
"dhcp_utilization": 0,
"disable": false,
"enable_ddns": false,
"extattrs": {"CITY": {"value": "city" },
"COUNTRY": {
"value": "ABC"
},
"Helpnow ID": {
"value": "TA"
"value": 0
}
},
"members": [],
"network": "10.158.2.0",
"utilization": 4
},{"0": {"_ref": "ipam:stat/ZGkMQ4LjEyLjAvMjIvMA:default/10.109.2.0/22",
"comment": "VLAN 0",
"dhcp_utilization": 0,
"disable": false,
"enable_ddns": false,
"extattrs": {
"CITY": {
"value": "city"
},
"COUNTRY": {
"value": "CDS"
},
"Helpnow ID": {
"value": "TA"
"value": 0
}
},
"members": [],
"network": "10.109.2.0",
"utilization": 9
}]
Solution 1:[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:[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:[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.
Solution 4:[4]
If I understood the question very well, the task is to turn a dictionary of dictionaries into a list of dictionaries without losing the structure of the data.
A list comprehension
would achieve this neatly where every item in the list is essentially a dictionary of a dictionary.
>>> dic_of_dicts = {1: {"a": "A"}, 2: {"b": "B"}, 3: {"c": "C"}}
>>> [{k: v} for k, v in dic_of_dicts.items()]
[{1: {'a': 'A'}}, {2: {'b': 'B'}}, {3: {'c': 'C'}}]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Van Peer |
Solution 2 | Kirby |
Solution 3 | |
Solution 4 | Citizen_7 |