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.
The function is fine IMO, clear and intuitive. But just to give you (another) answer, here is my go:
Can be useful for you or for anyone else..
Being late in my response is better than never!
Compare Not_Equal is more efficient than comparing Equal. As such two dicts are not equal if any key values in one dict is not found in the other dict. The code below takes into consideration that you maybe comparing default dict and thus uses get instead of getitem [].
Using a kind of random value as default in the get call equal to the key being retrieved - just in case the dicts has a None as value in one dict and that key does not exist in the other. Also the get != condition is checked before the not in condition for efficiency because you are doing the check on the keys and values from both sides at the same time.
In PyUnit there's a method which compares dictionaries beautifully. I tested it using the following two dictionaries, and it does exactly what you're looking for.
I'm not recommending importing
unittest
into your production code. My thought is the source in PyUnit could be re-tooled to run in production. It usespprint
which "pretty prints" the dictionaries. Seems pretty easy to adapt this code to be "production ready".I'm new to python but I ended up doing something similar to @mouad
The XOR operator (
^
) should eliminate all elements of the dict when they are the same in both dicts.The accepted answer and the most voted answers aren't the easiest way of answering the main question.
To check if two dictionaries are
equal
simply use==
, i.e.:dic1 == dic2
From python docs:
Valid for
py2
andpy3
.see dictionary view objects: https://docs.python.org/2/library/stdtypes.html#dict
This way you can subtract dictView2 from dictView1 and it will return a set of key/value pairs that are different in dictView2:
You can intersect, union, difference (shown above), symmetric difference these dictionary view objects.
Better? Faster? - not sure, but part of the standard library - which makes it a big plus for portability