Skip to content

Instantly share code, notes, and snippets.

@hit9
Created May 20, 2013 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hit9/5611962 to your computer and use it in GitHub Desktop.
Save hit9/5611962 to your computer and use it in GitHub Desktop.
Update a nested dict with another one.
a = {
'a': {
'x': 1,
'y': 2
},
'b': 3
}
b = {
'a': {
'x': 23
},
'b': 11,
'c': 13
}
# We want to get {'a': {'y': 2, 'x': 23}, 'c': 13, 'b': 11}
def update_nested_dict(a, b):
for k, v in b.items():
if isinstance(v, dict):
d = a.setdefault(k, {})
update_nested_dict(d, v)
else:
a[k] = v
return a
print update_nested_dict(a, b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment