Compare two nested dictionaries

Raymond Hettinger python at rcn.com
Sun Jul 25 13:20:01 EDT 2010


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

[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



More information about the Python-list mailing list