user225312 user225312 - 1 month ago 6
Python Question

Comparing two dictionaries in Python

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.

Answer

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

Maybe something like this:

shared_items = set(x.items()) & set(y.items())
print len(shared_items)