Created
December 7, 2018 20:12
-
-
Save cwells/380408d1e5a5ee6a99938c451d9d3560 to your computer and use it in GitHub Desktop.
deep merge two nested dictionaries, while applying a function to each item
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
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