Last active
April 1, 2023 00:38
-
-
Save ar852/9a9c18f5b1a620be53a19be3b204a24d to your computer and use it in GitHub Desktop.
merges two dictionaries with nested dictionaries inside of them without altering either of the original dictionaries
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 dict_merge(d1:dict, d2:dict, ret_dict:dict): | |
for k in sorted(set(d1.keys()).union(d2.keys())): | |
if k in d1 and k in d2: | |
if isinstance(d1[k], dict) and isinstance(d2[k], dict): | |
ret_dict[k] = {} | |
dict_merge(d1[k], d2[k], ret_dict[k]) | |
else: | |
ret_dict[k] = d2[k] | |
elif k in d2: | |
ret_dict[k] = d2[k] | |
else: | |
ret_dict[k] = d1[k] | |
return ret_dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If there is a value conflict for the same key, the function defaults to the value from d2