Skip to content

Instantly share code, notes, and snippets.

@burningsky250
Forked from angstwad/dict_merge.py
Created November 15, 2017 05:18
Show Gist options
  • Save burningsky250/081dcc8563358d889c5f8d33c7896a13 to your computer and use it in GitHub Desktop.
Save burningsky250/081dcc8563358d889c5f8d33c7896a13 to your computer and use it in GitHub Desktop.
Recursive dictionary merge in Python
import collections
def dict_merge(dct, merge_dct):
""" 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 ``merge_dct`` is merged into
``dct``.
:param dct: dict onto which the merge is executed
:param merge_dct: dct merged into dct
:return: None
"""
for k, v in merge_dct.iteritems():
if (k in dct and isinstance(dct[k], dict)
and isinstance(merge_dct[k], collections.Mapping)):
dict_merge(dct[k], merge_dct[k])
else:
dct[k] = merge_dct[k]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment