Search and Retrieve a Dictionary from a List Based on Specific Criteria
In Python, manipulating lists of dictionaries is a common task. One such scenario involves searching for and retrieving a specific dictionary based on its key-value pair.
Problem:
Consider the following list of dictionaries:
[ { "name": "Tom", "age": 10 }, { "name": "Mark", "age": 5 }, { "name": "Pam", "age": 7 } ]
How do we search for and retrieve the dictionary with the "name" key set to "Pam"?
Solution:
To solve this problem, we can utilize a generator expression, as demonstrated below:
dicts = [ { "name": "Tom", "age": 10 }, { "name": "Mark", "age": 5 }, { "name": "Pam", "age": 7 }, { "name": "Dick", "age": 12 } ] result = next(item for item in dicts if item["name"] == "Pam")
The generator expression iterates over each dictionary in the list and checks if its "name" key matches "Pam." If a match is found, the corresponding dictionary is returned and stored in the result variable. The next() function ensures that the first matching item is returned.
For example, running the above code snippet will retrieve the dictionary:
{'age': 7, 'name': 'Pam'}
Handling Item Not Found:
If the item is not found, you can handle it by providing a default using a slightly different API:
result = next((item for item in dicts if item["name"] == "Pam"), None)
The None argument ensures that the function returns None if no matching item is found.
Finding the Index of the Item:
To find the index of the matching item instead of the item itself, you can utilize the enumerate() function:
index = next((i for i, item in enumerate(dicts) if item["name"] == "Pam"), None)
The enumerate() function returns an iterator of tuples, where each tuple contains the index and the item. The generator expression uses this iterator to find the index of the first matching item and stores it in the index variable.
The above is the detailed content of How to Efficiently Find and Retrieve a Dictionary from a List in Python Based on Key-Value Matching?. For more information, please follow other related articles on the PHP Chinese website!