-
-
Save jsatt/c27a25ae9137a912447ff63fd04d4d5b to your computer and use it in GitHub Desktop.
Python dict deep merge
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
from copy import deepcopy | |
from functools import reduce | |
def merge_dicts(dict1: dict, dict2: dict) -> dict: | |
""" | |
Merges dicts. | |
""" | |
for key in dict2: | |
if key not in dict1 or not isinstance(dict1[key], dict): | |
dict1[key] = deepcopy(dict2[key]) | |
else: | |
dict1[key] = merge_dicts(dict1[key], dict2[key]) | |
return dict1 | |
def deep_merge_dicts(*dicts: dict, update: bool = False) -> dict: | |
""" | |
Merges dicts deeply. | |
""" | |
if update: | |
return reduce(merge_dicts, dicts[1:], dicts[0]) | |
return reduce(merge_dicts, dicts, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment