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

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

提交回复
热议问题