-
-
Save smithtrevor/354b4c6510c522466e82131b22b4e121 to your computer and use it in GitHub Desktop.
Recursive dictionary merge in Python without modifying original also Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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