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

前端 未结 7 688
自闭症患者
自闭症患者 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:40

    In [2]: test_list
    Out[2]: 
    [{'id': 'an id', 'title': 'some value', 'value': 123.40000000000001},
     {'id': 'another id', 'title': 'another title', 'value': 567.79999999999995},
     {'id': 'yet another id', 'title': 'last title', 'value': 901.20000000000005}]
    
    In [3]: [d for d in test_list if d["id"] == "an id"]
    Out[3]: [{'id': 'an id', 'title': 'some value', 'value': 123.40000000000001}]
    

    Use list comprehension

提交回复
热议问题