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

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

    You can create a simple function for this purpose:

    lVals = [{'title': 'some value', 'value': 123.4,'id': 'an id'},
     {'title': 'another title', 'value': 567.8,'id': 'another id'},
     {'title': 'last title', 'value': 901.2, 'id': 'yet another id'}]
    
    def get_by_id(vals, expId): return next(x for x in vals if x['id'] == expId)
    
    get_by_id(lVals, 'an id')
    >>> {'value': 123.4, 'title': 'some value', 'id': 'an id'}
    

提交回复
热议问题