Skip to content

Instantly share code, notes, and snippets.

@ksindi
Created June 12, 2016 17:33
Show Gist options
  • Save ksindi/950089095c0c9a16c2fa7f1d137220dd to your computer and use it in GitHub Desktop.
Save ksindi/950089095c0c9a16c2fa7f1d137220dd to your computer and use it in GitHub Desktop.
Recursively merge or update dict-like objects
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