pythondictionarycomparison

Comparing two dictionaries and checking how many (key, value) pairs are equal


I have two dictionaries, but for simplification, I will take these two:

>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)

Now, I want to compare whether each key, value pair in x has the same corresponding value in y. So I wrote this:

>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
        if x_values == y_values:
            print 'Ok', x_values, y_values
        else:
            print 'Not', x_values, y_values

And it works since a tuple is returned and then compared for equality.

My questions:

Is this correct? Is there a better way to do this? Better not in speed, I am talking about code elegance.

UPDATE: I forgot to mention that I have to check how many key, value pairs are equal.


Solution

  • If you want to know how many values match in both the dictionaries, you should have said that :)

    Maybe something like this:

    shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
    print(len(shared_items))