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
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.
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.
List comprehension is ideal for this:
[d for d in a if d['name'] == 'pluto']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With