Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of dictionaries search

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 ?

like image 817
Hellnar Avatar asked Dec 28 '11 08:12

Hellnar


People also ask

How do I iterate a list of dictionaries in Python?

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.

How do you check if a value is in a list of dictionaries Python?

Use any() & List comprehension to check if a value exists in a list of dictionaries.

How do I filter a dictionary list in Python?

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.


1 Answers

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) 
like image 178
Frédéric Hamidi Avatar answered Sep 22 '22 15:09

Frédéric Hamidi