Created
August 15, 2013 23:43
-
-
Save anfedorov/6246002 to your computer and use it in GitHub Desktop.
recursively diff two dicts
This file contains 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_dicts_recur(dict1, dict2, prefix=tuple()): | |
"""Takes the diff of two dicts, recursively.""" | |
for k, v in dict1.iteritems(): | |
if k not in dict2: | |
# only in dict1 | |
yield ('-', prefix + (k,), v) | |
else: | |
w = dict2[k] | |
if w != v: # in both, but different values | |
if isinstance(w, dict) and isinstance(v, dict): | |
for x in diff_dicts_recur(v, w, prefix + (k,)): | |
yield x | |
else: | |
yield ('-', prefix + (k,), v) | |
yield ('+', prefix + (k,), w) | |
for k in dict2.keys(): | |
if k not in dict1: | |
# only in dict2 | |
yield ('+', prefix + (k,), dict2[k]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment