Find the index of a dict within a list, by matching the dict's value

后端 未结 10 568
死守一世寂寞
死守一世寂寞 2020-11-28 18:56

I have a list of dicts:

list = [{\'id\':\'1234\',\'name\':\'Jason\'},
        {\'id\':\'2345\',\'name\':\'Tom\'},
        {\'id\':\'3456\',\'name\':\'Art\'}]         


        
10条回答
  •  北海茫月
    2020-11-28 19:19

    lst = [{'id':'1234','name':'Jason'}, {'id':'2345','name':'Tom'}, {'id':'3456','name':'Art'}]
    
    tom_index = next((index for (index, d) in enumerate(lst) if d["name"] == "Tom"), None)
    # 1
    

    If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:

    def build_dict(seq, key):
        return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))
    
    info_by_name = build_dict(lst, key="name")
    tom_info = info_by_name.get("Tom")
    # {'index': 1, 'id': '2345', 'name': 'Tom'}
    

提交回复
热议问题