# Compare two nested dictionaries

T

#### targetsmart

Hi,
I am trying to compare two nested dictionaries, I want to know what is
the exact difference between them. I tried this solution

....
s1 = set(result1)
s2 = set(result2)
print s1 - s2

but it doesn't seem show any difference, but

assert result1 == result2
fails

could someone help me to find out the difference the two nested
dictionaries.

Any help is greatly appreciated.

Thanks,
Vivek.

S

#### Steven D'Aprano

Hi,
I am trying to compare two nested dictionaries, I want to know what is
the exact difference between them. I tried this solution

...
s1 = set(result1)
s2 = set(result2)
print s1 - s2

but it doesn't seem show any difference, but

assert result1 == result2
fails

could someone help me to find out the difference the two nested
dictionaries.

Have you tried printing them and just looking for the differences?

Calling set() on a dictionary will create a set from the keys only:
False

If you want to know the difference between two dictionaries, you have to
consider:

(1) Keys that are in the first dict, but not the second;

(2) Keys that are in the second dict, but not the first; and

(3) Keys which are in both dicts, but have different values.

N

#### News123

Hi,

I think you want to have the symmetric difference:
try s1 ^ s2

R

#### Raymond Hettinger

[targetsmart]
[Steven D'Aprano]
If you want to know the difference between two dictionaries, you have to
consider:

(1) Keys that are in the first dict, but not the second;

(2) Keys that are in the second dict, but not the first; and

(3) Keys which are in both dicts, but have different values.

Steven, thanks for the excellent specification. Here's the code:

s1 = set(d1)
s2 = set(d2)
first_not_second = s1 - s2
second_not_first = s2 - s1
difference_values = set(k for k in s1 & s2 if d1[k] != d2[k])

If the values are hashable, an alternate approach is:

s1 = set(d1.items())
s2 = set(d2.items())
first_not_second = s1 - s2
second_not_first = s2 - s1

Raymond

J

#### John Nagle

Hi,
I am trying to compare two nested dictionaries, I want to know what is
the exact difference between them.

d1 = {'a' : 1, 'b' : 2, 'c': 3 }
d2 = {'a' : 1, 'b' : 3, 'd': 4 }

diff = dict(set(d1.items()) - set(d2.items()))

print (diff)

{'c': 3, 'b': 2}

That's the true "difference", with all entries in d1 not
identically in d2 listed. Is that what you wanted?

John Nagle

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.