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

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

    Here's a function that finds the dictionary's index position if it exists.

    dicts = [{'id':'1234','name':'Jason'},
             {'id':'2345','name':'Tom'},
             {'id':'3456','name':'Art'}]
    
    def find_index(dicts, key, value):
        class Null: pass
        for i, d in enumerate(dicts):
            if d.get(key, Null) == value:
                return i
        else:
            raise ValueError('no dict with the key and value combination found')
    
    print find_index(dicts, 'name', 'Tom')
    # 1
    find_index(dicts, 'name', 'Ensnare')
    # ValueError: no dict with the key and value combination found
    

提交回复
热议问题