Skip to content

Instantly share code, notes, and snippets.

@anfedorov
Created August 15, 2013 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anfedorov/6246002 to your computer and use it in GitHub Desktop.
Save anfedorov/6246002 to your computer and use it in GitHub Desktop.
recursively diff two dicts
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