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.
What you want to do is simply
x==y
What you do is not a good idea, because the items in a dictionary are not supposed to have any order. You might be comparing
[('a',1),('b',1)]
with[('b',1), ('a',1)]
(same dictionaries, different order).For example, see this:
The difference is only one item, but your algorithm will see that all items are different
If you want to know how many values match in both the dictionaries, you should have said that :)
Maybe something like this:
Yet another possibility, up to the last note of the OP, is to compare the hashes (
SHA
orMD
) of the dicts dumped as JSON. The way hashes are constructed guarantee that if they are equal, the source strings are equal as well. This is very fast and mathematically sound.To test if two dicts are equal in keys and values:
If you want to return the values which differ, write it differently:
You would have to call it twice i.e
Here's another option:
So as you see the two id's are different. But the rich comparison operators seem to do the trick:
Code
Test