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

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

    It won't be efficient, as you need to walk the list checking every item in it (O(n)). If you want efficiency, you can use dict of dicts. On the question, here's one possible way to find it (though, if you want to stick to this data structure, it's actually more efficient to use a generator as Brent Newey has written in the comments; see also tokland's answer):

    >>> L = [{'id':'1234','name':'Jason'},
    ...         {'id':'2345','name':'Tom'},
    ...         {'id':'3456','name':'Art'}]
    >>> [i for i,_ in enumerate(L) if _['name'] == 'Tom'][0]
    1
    

提交回复
热议问题