Find the index of a partial dictionary item in a list

I have a list of dictionaries as follows:

myList=[{'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'}, 
        {'id':6,'key1':'a','key2':'p'}]

To find the index of an element, I am currently executing the following statement:

print myList.index({'id':8,'key1':'c','key2':'d'})

which returns 1

However, I would like to do something like this:

print myList.index({'id':8})

must return 1

+3
source share
4 answers

It should be relatively easy to implement. Written for Python 3, in Python 2, you should use .iteritems()(does not create a temporary list).

def partial_dict_index(dicts, dict_part):
    for i, current_dict in enumerate(dicts):
        # if this dict has all keys required and the values match
        if all(key in current_dict and current_dict[key] == val 
                for key, val in dict_part.items()):
            return i
    raise ValueError("...")

They can use better names, though ...

+1
source

If you are looking for a single line (as opposed to reusable code) and the data size is small, you can do something like:

[elem["id"] for elem in myList].index(8)

dict, . , , , ...

+1

Edit: Please change the accepted answer to the @delnan fixed answer, which is very similar and probably works better.

+1
source

You can implement your own list. Here is an example that prints the first result found. I added a ValueError to duplicate the existing .index () behavior.

class DictList(list):

    def index(self, obj):
        for i, o in enumerate(self):
            if o['id'] == obj['id']:
                return i
        else:
            raise ValueError('x not in list')


myList = DictList(({'id':1,'key1':'a','key2':'b'},{'id':8,'key1':'c','key2':'d'}, 
                   {'id':6,'key1':'a','key2':'p'}))

>>> print myList.index({'id': 8})
1

>>> print myList.index({'id': 10})
ValueError: x not in list
-1
source

Source: https://habr.com/ru/post/1774362/


All Articles