Assume I have this:
[ {"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7} ]
and by searching "Pam" as name, I want to retrieve the related dictionary: {name: "Pam", age: 7}
How to achieve this ?
There are multiple ways to iterate through list of dictionaries in python. Basically, you need to use a loop inside another loop. The outer loop, iterates through each dictionary, while the inner loop iterates through the individual elements of each dictionary.
Use any() & List comprehension to check if a value exists in a list of dictionaries.
We can easily search a list of dictionaries for an item by using the filter() function with a lambda function. In Python3, the filter() function returns an object of the filter class. We can convert that object into a list with the list() function.
You can use a generator expression:
>>> dicts = [ ... { "name": "Tom", "age": 10 }, ... { "name": "Mark", "age": 5 }, ... { "name": "Pam", "age": 7 }, ... { "name": "Dick", "age": 12 } ... ] >>> next(item for item in dicts if item["name"] == "Pam") {'age': 7, 'name': 'Pam'}
If you need to handle the item not being there, then you can do what user Matt suggested in his comment and provide a default using a slightly different API:
next((item for item in dicts if item["name"] == "Pam"), None)
And to find the index of the item, rather than the item itself, you can enumerate() the list:
next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)
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