dict diff

Jin Yi razamatan_retral_net at nospam.com
Sat Nov 20 21:33:55 CET 2010


right.  i moved to a 2-value tuple return value basically to illustrate exactly where each dict is providing a different value.  it turns out to be much easier to grok than the 3-value one since it's all there and lines up correctly with the inputs...

On Sat, Nov 20, 2010 at 12:00:16PM +0000, Steven D'Aprano wrote:
> On Sat, 20 Nov 2010 01:11:53 -0500, Steve Holden wrote:
> 
> > On 11/19/2010 8:58 PM, Jin Yi wrote:
> >> so i came up with a diff method to compare 2 dicts. 
> [...]
> > A PEP *and* some explanation of why you would want such an obscure piece
> > of code built in to the dict object, yes.
> 
> You've never wanted to see how two dicts differ, as well as the fact that 
> they do? I frequently find myself wanting to see why two dicts that 
> should be equal aren't, especially for testing and debugging.
> 
> I use this function:
> 
> def dict_diffs(a, b):
>     """dict_diffs(adict, bdict) -> (amissing, bmissing, different)
> 
>     Returns sets (amissing, bmissing, different) such that:
> 
>     amissing = keys missing from adict compared to bdict
>     bmissing = keys missing from bdict compared to adict
>     different = keys in both adict and bdict but with different values
> 
>     >>> dict_diffs({1:0, 2:0, 3:0}, {1:1, 2:0, 4:0})
>     (set([4]), set([3]), set([1]))
> 
>     """
>     from collections import Mapping
>     if not isinstance(a, Mapping) and isinstance(b, Mapping):
>         raise TypeError('arguments must both be mappings')
>     amissing, bmissing, different = set(), set(), set()
>     for key, value in a.items():
>         if key not in b:
>             bmissing.add(key)
>         elif value != b[key]:
>             different.add(key)
>     for key, value in b.items():
>         if key not in a:
>             amissing.add(key)
>     return (amissing, bmissing, different)
> 
> 
> -- 
> Steven
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-- 
I pops mah collah.  (Busta Rhymes)
Jin Yi -- http://www.retral.net/razamatan



More information about the Python-list mailing list