pythonperformancelistdictionary

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


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


Solution

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