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
}]
Python's dictionary class has three methods for this purpose. The methods items(), keys() and values() return view objects comprising of tuple of key-value pairs, keys only and values only respectively. The in-built list method converts these view objects in list objects.
keys() This task can also be performed. In this, we get the keys value of dict and iterate over the list of keys and get the values of corresponding values and concatenate both key and value, and form a list of lists.
To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function. See the following article for more information.
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'}]
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With