dict diff
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Nov 20 07:00:16 EST 2010
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
More information about the Python-list
mailing list