Skip to content

Instantly share code, notes, and snippets.

@smithtrevor
Forked from angstwad/dict_merge.py
Last active April 4, 2018 21:09
Show Gist options
  • Select an option

  • Save smithtrevor/354b4c6510c522466e82131b22b4e121 to your computer and use it in GitHub Desktop.

Select an option

Save smithtrevor/354b4c6510c522466e82131b22b4e121 to your computer and use it in GitHub Desktop.
Recursive dictionary merge in Python without modifying original also Python 3
import collections
def dict_merge(orig, changes):
""" Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
updating only top-level keys, dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys. The ``changes`` is merged with
``orig`` and returned as ``dct``
:param orig: dict onto which the merge is executed
:param changes: dct merged into dct
:return: dict
"""
dct = orig.copy()
merge_dct = changes.copy()
for k, v in merge_dct.items():
if (k in dct and isinstance(dct[k], dict) and isinstance(merge_dct[k], collections.Mapping)):
dct[k] = dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]
return dct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment