Skip to content

Instantly share code, notes, and snippets.

@toast254
Forked from angstwad/dict_merge.py
Last active May 16, 2017 13:39
Show Gist options
  • Save toast254/0d1952861116cd87629defabddf7c789 to your computer and use it in GitHub Desktop.
Save toast254/0d1952861116cd87629defabddf7c789 to your computer and use it in GitHub Desktop.
Recursive dictionary merge in Python 3
# -*- coding: utf-8 -*-
import collections
def dict_merge(dct: dict, merge_dct: dict):
""" 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``.
:type dct: dict
:param dct: dict onto which the merge is executed
:type merge_dct: dict
:param merge_dct: dct merged into dct
"""
for k, v in merge_dct.items():
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