Categories
Python Answers

How to search a list of dictionaries with Python?

Spread the love

Sometimes, we want to search a list of dictionaries with Python.

In this article, we’ll look at how to search a list of dictionaries with Python.

How to search a list of dictionaries with Python?

To search a list of dictionaries with Python, we can use list comprehension and the next function.

For instance, we write:

dicts = [{
    "name": "Tom",
    "age": 10
}, {
    "name": "Mark",
    "age": 5
}, {
    "name": "Pam",
    "age": 7
}]

d = next((item for item in dicts if item["name"] == "Pam"), None)
print(d)

to get get the dictionary with the name key set to 'Pam' with item for item in dicts if item["name"] == "Pam".

Then we get the first entry that matches with next.

We return None if there’re no matches.

Therefore, d is {'name': 'Pam', 'age': 7}.

Conclusion

To search a list of dictionaries with Python, we can use list comprehension and the next function.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *