Skip to content

Instantly share code, notes, and snippets.

@ar852
Last active April 1, 2023 00:38
Show Gist options
  • Save ar852/9a9c18f5b1a620be53a19be3b204a24d to your computer and use it in GitHub Desktop.
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
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
@ar852
Copy link
Author

ar852 commented Apr 1, 2023

If there is a value conflict for the same key, the function defaults to the value from d2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment