Skip to content

Instantly share code, notes, and snippets.

@cwells
Created December 7, 2018 20:12
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 cwells/380408d1e5a5ee6a99938c451d9d3560 to your computer and use it in GitHub Desktop.
Save cwells/380408d1e5a5ee6a99938c451d9d3560 to your computer and use it in GitHub Desktop.
deep merge two nested dictionaries, while applying a function to each item
import collections
def deep_fn_merge(fn, left, right):
for k, v in right.iteritems():
if k in left and isinstance(left[k], dict) and isinstance(right[k], collections.Mapping):
deep_fn_merge(fn, left[k], right[k])
else:
left[k] = fn(left, right, k)
def sum(left, right, key):
return left.get(key, 0) + right.get(key, 0)
d1 = { 'a': 1, 'b': 2, 'c': 3, 'd': { 'e': 10, 'f': 4 } }
d2 = { 'a': 0, 'b': 6, 'd': { 'e': 10, 'g': 3 } }
deep_fn_merge(sum, d1, d2)
print d1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment