Created
October 7, 2012 01:34
-
-
Save Suor/3846779 to your computer and use it in GitHub Desktop.
A dicts diff and patch utilities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def diff(old, new): | |
""" | |
diff(a, b) = b - a | |
a + diff(a, b) == b | |
""" | |
return strip_dict(map_dicts(diff_atom, old, new)) | |
def diff_atom(old, new): | |
return None if old == new else (old, new) | |
def patch(old, diff): # -> new | |
return map_dicts(atom_patch, old, diff) | |
def atom_patch(value, (old, new)): | |
assert value == old | |
return new | |
def patchback(new, diff): # -> old | |
pass | |
### tools | |
def strip_dict(d): | |
return {k: v for k, v in d.iteritems() if v is not None} | |
def map_dicts(func, d1, d2): | |
return {key: func(v1, v2) for key, v1, v2 in iterate_dicts(d1, d2)} | |
def iterate_dicts(d1, d2): | |
keys = set(d1) | set(d2) | |
for key in keys: | |
yield key, d1.get(key), d2.get(key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment