Skip to content

Instantly share code, notes, and snippets.

@yatsu
Created April 28, 2018 13:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yatsu/68660bea18edfe7e023656c250661086 to your computer and use it in GitHub Desktop.
Save yatsu/68660bea18edfe7e023656c250661086 to your computer and use it in GitHub Desktop.
Python dict deep merge
from copy import deepcopy
from functools import reduce
def deep_merge(*dicts, update=False):
"""
Merges dicts deeply.
Parameters
----------
dicts : list[dict]
List of dicts.
update : bool
Whether to update the first dict or create a new dict.
Returns
-------
merged : dict
Merged dict.
"""
def merge_into(d1, d2):
for key in d2:
if key not in d1 or not isinstance(d1[key], dict):
d1[key] = deepcopy(d2[key])
else:
d1[key] = merge_into(d1[key], d2[key])
return d1
if update:
return reduce(merge_into, dicts[1:], dicts[0])
else:
return reduce(merge_into, dicts, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment