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

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

    Answer offered by @faham is a nice one-liner, but it doesn't return the index to the dictionary containing the value. Instead it returns the dictionary itself. Here is a simple way to get: A list of indexes one or more if there are more than one, or an empty list if there are none:

    list = [{'id':'1234','name':'Jason'},
            {'id':'2345','name':'Tom'},
            {'id':'3456','name':'Art'}]
    
    [i for i, d in enumerate(list) if 'Tom' in d.values()]
    

    Output:

    >>> [1]
    

    What I like about this approach is that with a simple edit you can get a list of both the indexes and the dictionaries as tuples. This is the problem I needed to solve and found these answers. In the following, I added a duplicate value in a different dictionary to show how it works:

    list = [{'id':'1234','name':'Jason'},
            {'id':'2345','name':'Tom'},
            {'id':'3456','name':'Art'},
            {'id':'4567','name':'Tom'}]
    
    [(i, d) for i, d in enumerate(list) if 'Tom' in d.values()]
    

    Output:

    >>> [(1, {'id': '2345', 'name': 'Tom'}), (3, {'id': '4567', 'name': 'Tom'})]
    

    This solution finds all dictionaries containing 'Tom' in any of their values.

提交回复
热议问题