Home >Backend Development >Python Tutorial >How to Efficiently Search for a Specific Dictionary in a Python List of Dictionaries?
Searching Dictionaries in a List Using Python
Consider a list of dictionaries as an example:
dicts = [ {"name": "Tom", "age": 10}, {"name": "Mark", "age": 5}, {"name": "Pam", "age": 7}, ]
Problem: How do you search for and retrieve the dictionary where the "name" key equals "Pam"?
Solution:
Using a generator expression, you can iterate over the list of dictionaries and filter out the one you need:
match = next(item for item in dicts if item["name"] == "Pam") print(match) # {"name": "Pam", "age": 7}
Handling Non-Existence:
If it's possible that the name you're searching for doesn't exist in the list, you can use the next() function with a default argument:
match = next((item for item in dicts if item["name"] == "Pam"), None) if match: print(match) else: print("No matching dictionary found.")
Alternative Approaches:
index = next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None) print(f"Matching dictionary at index {index}")
The above is the detailed content of How to Efficiently Search for a Specific Dictionary in a Python List of Dictionaries?. For more information, please follow other related articles on the PHP Chinese website!