What's the cleanest way to compare 2 dictionary?

John Henry john106henry at hotmail.com
Wed Aug 9 17:59:11 EDT 2006


John Henry wrote:
> Paddy wrote:
> > John Henry wrote:
> > > Hi list,
> > >
> > > I am sure there are many ways of doing comparision but I like to see
> > > what you would do if you have 2 dictionary sets (containing lots of
> > > data - like 20000 keys and each key contains a dozen or so of records)
> > > and you want to build a list of differences about these two sets.
> > >
> > > I like to end up with 3 lists: what's in A and not in B, what's in B
> > > and not in A, and of course, what's in both A and B.
> > >
> > > What do you think is the cleanest way to do it?  (I am sure you will
> > > come up with ways that astonishes me  :=) )
> > >
> > > Thanks,
> > I make it 4 bins:
> >  a_exclusive_keys
> >  b_exclusive_keys
> >  common_keys_equal_values
> >  common_keys_diff_values
> >
> > Something like:
> >
> > a={1:1, 2:2,3:3,4:4}
> > b = {2:2, 3:-3, 5:5}
> > keya=set(a.keys())
> > keyb=set(b.keys())
> > a_xclusive = keya - keyb
> > b_xclusive = keyb - keya
> > _common = keya & keyb
> > common_eq = set(k for k in _common if a[k] == b[k])
> > common_neq = _common - common_eq
> >
> >
> > If you now simple set arithmatic, it should read OK.
> >
> > - Paddy.
>
> Thanks, that's very clean.  Give me good reason to move up to Python
> 2.4.

Oh, wait, works in 2.3 too.

Just have to:

from sets import Set as set




More information about the Python-list mailing list