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

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

    If you have to do this multiple times, you should recreate a dictionnary indexed by id with your list :

    keys = [item['id'] for item in initial_list]
    new_dict = dict(zip(keys, initial_list)) 
    
    >>>{
        'yet another id': {'id': 'yet another id', 'value': 901.20000000000005, 'title': 'last title'}, 
        'an id': {'id': 'an id', 'value': 123.40000000000001, 'title': 'some value'}, 
        'another id': {'id': 'another id', 'value': 567.79999999999995, 'title': 'another title'}
    }
    

    or in a one-liner way as suggested by agf :

    new_dict = dict((item['id'], item) for item in initial_list)
    
    0 讨论(0)
提交回复
热议问题