Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a key's value from a list of dictionaries python

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'])
like image 452
Boosted_d16 Avatar asked Feb 14 '14 15:02

Boosted_d16


People also ask

How do you get a specific value from a dictionary in Python?

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.

How do you check if a value is in a list of dictionaries?

Use any() & List comprehension to check if a value exists in a list of dictionaries.


1 Answers

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"]
like image 158
Kevin Avatar answered Nov 28 '22 16:11

Kevin