Skip to content

Instantly share code, notes, and snippets.

@ArthurDelannoyazerty
Created March 27, 2024 10:38
Show Gist options
  • Select an option

  • Save ArthurDelannoyazerty/6a8ef4d406e63b0768e576deabe5e170 to your computer and use it in GitHub Desktop.

Select an option

Save ArthurDelannoyazerty/6a8ef4d406e63b0768e576deabe5e170 to your computer and use it in GitHub Desktop.
Merge nested dict recursively
def merge(a:dict, b:dict, path=[]):
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path + [str(key)])
elif a[key] != b[key]:
raise Exception('Conflict at ' + '.'.join(path + [str(key)]))
else:
a[key] = b[key]
return a
dicts = [dict1, dict2,dict3]
merged_dict = reduce(merge, dicts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment