extract item from list of dictionaries

Question:

Suppose you have a list of dictionaries like this one:

a = [ {'name':'pippo', 'age':'5'} , {'name':'pluto', 'age':'7'} ]

What do you to extract from this list only the dict where name==pluto?
To make things a little bit harder, consider that I cannot do any import

Asked By: Ottavio Campana

||

Answers:

List comprehension is ideal for this:

[d for d in a if d['name'] == 'pluto']
Answered By: rplnt
[d for d in a if d['name'] == 'pluto']
Answered By: Michael Brennan
>>> [d['age'] for d in a if d['name']=='pluto']
['7']
Answered By: Karoly Horvath

Use a list comprehension which picks out the correct dict in the list of dicts.

 >>> [d for d in a if d['name']=='pluto']
 [{'age': '7', 'name': 'pluto'}]

Or, if you’re not sure if all of the dicts in a have a ‘name’ key,

 >>> [d for d in a if d.get('name')=='pluto']
 [{'age': '7', 'name': 'pluto'}]

Note that both of these return a list. If you know that there is only one matching entry, you can add [0] to the end to return the actual dict:

 >>> [d for d in a if d['name']=='pluto'][0]
 {'age': '7', 'name': 'pluto'}
Answered By: Andrew Jaffe

Apart from list comprehension that other responses give it to you, you can also do it with a filter and a lambda:

filter(lambda x: x.get('name') == 'pluto',a)
Answered By: Mikel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.