How do I get a given key's value from a list of dictionaries?
mylist = [
{
'powerpoint_color': 'blue',
'client_name': 'Sport Parents (Regrouped)'
},
{
'sort_order': 'ascending',
'chart_layout': '1',
'chart_type': 'bar'
}
]
The number of dictionaries in mylist
is unknown and I want to find the value attached to the key 'sort_order'
.
My failed attempt:
for key in mylist:
for value in key:
print(key['sort_order'])
In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.
Use any() & List comprehension to check if a value exists in a list of dictionaries.
mylist= [{'powerpoint_color': 'blue', 'client_name': 'Sport Parents (Regrouped)'}, {'sort_order': 'ascending', 'chart_layout': '1', 'chart_type': 'bar'}]
print [d["sort_order"] for d in mylist if "sort_order" in d][0]
Result:
ascending
You could also combine all of the dictionaries into a single dict, and access that:
combined_d = {key: value for d in mylist for key,value in d.iteritems() }
print combined_d["sort_order"]
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