-
@ian-partridge’s solution is great, but what if you want to stop searching as soon as you find the first match? The
next()function with a generator expression is perfect for this.* This approach is highly efficient for searching in a list of dictionaries in Python, especially when you only need the first match:
data = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]
result = next((item for item in data if item['name'] == "Pam"), None)
print(result)
Using next() with a generator expression ensures that the iteration stops as soon as a match is found, which is particularly useful when dealing with large datasets.