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

前端 未结 7 669
自闭症患者
自闭症患者 2020-11-30 23:56

I need to be able to find an item in a list (an item in this case being a dict) based on some value inside that dict. The structure o

7条回答
  •  温柔的废话
    2020-12-01 00:20

    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.

提交回复
热议问题