Alex Rivera | Logout

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

Asked 2011-08-16T13:53:25.280
106

I need to find a dict in this list based on a unique value (id) inside that dict:

[
    {
        'title': 'some value',
        'value': 123.4,
        'id': 'an id'
    },
    {
        'title': 'another title',
        'value': 567.8,
        'id': 'another id'
    }
]

Caveats: title and value can be any value (and the same), id would be unique.

I know this can be done through the use of loops, but this seems cumbersome

Edit
Report

1 Answer

167
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.

answered 2011-08-16T13:57:34.247

Your Answer