Skip to content

Instantly share code, notes, and snippets.

@jsatt
Forked from yatsu/deep_merge.py
Last active August 26, 2020 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsatt/c27a25ae9137a912447ff63fd04d4d5b to your computer and use it in GitHub Desktop.
Save jsatt/c27a25ae9137a912447ff63fd04d4d5b to your computer and use it in GitHub Desktop.
Python dict deep merge
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