Created
June 12, 2016 17:33
-
-
Save ksindi/950089095c0c9a16c2fa7f1d137220dd to your computer and use it in GitHub Desktop.
Recursively merge or update dict-like objects
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 update(d, other): | |
"""Recursively merge or update dict-like objects. | |
>>> from pprint import pprint | |
>>> pprint(update({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4})) | |
{'k1': {'k2': {'k3': 3}}, 'k4': 4} | |
>>> pprint(update({'k1': {'k2': 2}}, {'k1': {'k3': 3}})) | |
{'k1': {'k2': 2, 'k3': 3}} | |
>>> pprint(update({'k1': {'k2': 2}}, dict())) | |
{'k1': {'k2': 2}} | |
""" | |
for k, v in other.items(): | |
if isinstance(d, collections.Mapping): | |
if isinstance(v, collections.Mapping): | |
r = update(d.get(k, {}), v) | |
d[k] = r | |
else: | |
d[k] = other[k] | |
else: | |
d = {k: other[k]} | |
return d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment