Skip to content

Instantly share code, notes, and snippets.

@ionymikler
Created December 18, 2024 10:39
Show Gist options
  • Save ionymikler/39f27aa5c4e248b704e353680f678f78 to your computer and use it in GitHub Desktop.
Save ionymikler/39f27aa5c4e248b704e353680f678f78 to your computer and use it in GitHub Desktop.
recursve merging of dictionaries
def merge_dicts(a: dict, b: dict, path: List[str] = [], update: bool = True) -> dict:
"""
Merge two dictionaries recursively.
:param a: The first dictionary.
:param b: The second dictionary.
:param path: The path to the current key.
:param update: If True, the value in dictionary 'b' will replace that in 'a' on conflict,
otherwise an exception will be raised.
"""
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_dicts(a[key], b[key], path + [str(key)])
elif a[key] != b[key]:
if update:
a[key] = b[key]
else:
raise Exception("Conflict at " + ".".join(path + [str(key)]))
else:
a[key] = b[key]
return a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment