Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract item from list of dictionaries

Tags:

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

like image 927
Ottavio Campana Avatar asked Oct 26 '11 09:10

Ottavio Campana


People also ask

How do I iterate a list of dictionaries in Python?

In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example. You can iterate keys by using the dictionary object directly in a for loop.

How do you get a list of all the values in a dictionary?

To obtain the list, we can utilise dictionary. values() in conjunction with the list() function. The values() method is used to access values from the key: value pairs and the values are then converted to a list using the list() function.


1 Answers

List comprehension is ideal for this:

[d for d in a if d['name'] == 'pluto'] 
like image 183
rplnt Avatar answered Oct 14 '22 00:10

rplnt