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
Answers:
List comprehension is ideal for this:
[d for d in a if d['name'] == 'pluto']
[d for d in a if d['name'] == 'pluto']
>>> [d['age'] for d in a if d['name']=='pluto']
['7']
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'}
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)
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
List comprehension is ideal for this:
[d for d in a if d['name'] == 'pluto']
[d for d in a if d['name'] == 'pluto']
>>> [d['age'] for d in a if d['name']=='pluto']
['7']
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'}
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)