'How to find a key's value from a list of dictionaries?
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'])
Solution 1:[1]
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"]
Solution 2:[2]
You can get it using this code:
for d in mylist:
if 'sort_order' in d:
print(d['sort_order'])
First you iterate over list, for each dictionary check if it has needed key and if it does get value.
Solution 3:[3]
Something like that ?
for hash in mylist:
if "sort_order" in hash: print hash ["sort_order"]
Solution 4:[4]
While not as readable, this version:
- provides short-circuiting
- avoids a double lookup
print reduce( lambda a,b: a or b, (l.get("sort_order") for l in mylist) )
Note that this would fail if some of your keys evaluated to false, but it's not hard to develop a version that doesn't from this starting point
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 | Kevin |
| Solution 2 | rsk |
| Solution 3 | elhostis |
| Solution 4 | loopbackbee |
