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 the next function.

For instance, we write

dicts = [
    {"name": "jane", "age": 10},
    {"name": "mark", "age": 5},
    {"name": "john", "age": 7},
    {"name": "alex", "age": 12},
]

next(item for item in dicts if item["name"] == "jane")

to call next with an the items returned by the item for item in dicts if item["name"] == "jane" list to get the first item in dicts that has the dict entry with key name set to 'jane'.

Conclusion

To search a list of dictionaries with Python, we can use 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 *