Created
March 27, 2024 10:38
-
-
Save ArthurDelannoyazerty/6a8ef4d406e63b0768e576deabe5e170 to your computer and use it in GitHub Desktop.
Merge nested dict recursively
This file contains hidden or 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 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