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

后端 未结 10 469
死守一世寂寞
死守一世寂寞 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:04

    A simple readable version is

    def find(lst, key, value):
        for i, dic in enumerate(lst):
            if dic[key] == value:
                return i
        return -1
    
    0 讨论(0)
  • 2020-11-28 19:08

    One liner!?

    elm = ([i for i in mylist if i['name'] == 'Tom'] or [None])[0]
    
    0 讨论(0)
  • 2020-11-28 19:16

    Seems most logical to use a filter/index combo:

    names=[{}, {'name': 'Tom'},{'name': 'Tony'}]
    names.index(filter(lambda n: n.get('name') == 'Tom', names)[0])
    1
    

    And if you think there could be multiple matches:

    [names.index(n) for item in filter(lambda n: n.get('name') == 'Tom', names)]
    [1]
    
    0 讨论(0)
  • 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'}
    
    0 讨论(0)
  • 2020-11-28 19:19
    def search(itemID,list):
         return[i for i in list if i.itemID==itemID]
    
    0 讨论(0)
  • 2020-11-28 19:23

    I needed a more general solution to account for the possibility of multiple dictionaries in the list having the key value, and a straightforward implementation using list comprehension:

    dict_indices = [i for i, d in enumerate(dict_list) if d[dict_key] == key_value] 
    
    0 讨论(0)
提交回复
热议问题