Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save LeaveNhA/0b8ae81974497689b5196cca7f9e3859 to your computer and use it in GitHub Desktop.
Save LeaveNhA/0b8ae81974497689b5196cca7f9e3859 to your computer and use it in GitHub Desktop.
In Python, you can merge two nested dicts or apply functions over them even if them nested, yes!
def apply_with(d, fn=lambda x: x):
res = d.copy() # "= dict(d1)" for lists of tuples
for key, val in res.items():
if type(res[key]) is dict:
res[key] = apply_with(res[key], fn)
else:
res[key] = fn(res[key])
return res
def merge_with(d1, d2, fn=lambda x, y: x + y):
# print("---------merging---------")
# print('d1: {}, d2: {}'.format(d1, d2))
res = d1.copy() # "= dict(d1)" for lists of tuples
for key, val in d2.items(): # ".. in d2" for lists of tuples
try:
if type(res[key]) is dict:
#print('dict')
#print(key)
#print(res[key])
res[key] = merge_with(res[key], val, fn)
else:
#print('scaler')
#print(key)
res[key] = fn(res[key], val)
#print(res[key])
except: #KeyError:res[key] = val
pass
#print("res: {}".format(res))
#print("--------------------")
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment