>>> dicts = [ { "name": "Tom", "age": 10 }, { "name": "Mark", "age": 5 }, { "name": "Pam", "age": 7 }, { "name": "Dick", "age": 12 } ] >>> next(item for item in dicts if item["name"] == "Pam") {'age': 7, 'name': 'Pam'} # WITH DEFAULT VALUE TO None if None next((item for item in dicts if item["name"] == "pam"), None)
Here is what the above code is Doing:
1. It’s creating a generator expression, which is a generator that yields one item at a time.
2. It’s iterating over the list of dictionaries.
3. It’s checking if the name of the dictionary is equal to “Pam”.
4. It’s returning the first dictionary that matches the condition.
5. It’s using the built-in next() function to get the next item from the generator.
6. It’s using the built-in list() function to convert the generator into a list.