Python: get a dict from a list based on something inside the dict

my_item = next((item for item in my_list if item['id'] == my_unique_id), None)

This iterates through the list until it finds the first item matching my_unique_id, then stops. It doesn’t store any intermediate lists in memory (by using a generator expression) or require an explicit loop. It sets my_item to None of no object is found. It’s approximately the same as

for item in my_list:
    if item['id'] == my_unique_id:
        my_item = item
        break
else:
    my_item = None

else clauses on for loops are used when the loop is not ended by a break statement.

Leave a Comment