Created
July 13, 2022 23:06
-
-
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!
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 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