user225312 user225312 - 1 year ago 149
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
has the same corresponding value in
. 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
print 'Not', x_values, y_values

And it works since a
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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download