Last active
October 26, 2015 15:27
-
-
Save mbaltrusitis/e51e9f0af4c46bf6a959 to your computer and use it in GitHub Desktop.
Update Variable Depth Dictionary
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 | |
from pprint import pprint | |
my_dict = { | |
'one': { | |
'one-one': True, | |
'one-two': False, | |
'one-three': { | |
'one-three-one': True, | |
}, | |
}, | |
'two': { | |
'two-one': True, | |
}, | |
} | |
def update_dict(main, update): | |
for k, v in update.items(): | |
if isinstance(v, collections.Mapping): | |
r = update_dict(main.get(k, {}), v) | |
main[k] = r | |
else: | |
main[k] = update[k] | |
return main | |
if __name__ == '__main__': | |
print('Original dictionary') | |
pprint(my_dict) | |
my_update = { | |
'one': { | |
'one-three': { | |
'one-three-two': True, | |
'one-three-one': False, | |
'one-three-three': 'new', | |
} | |
} | |
} | |
print('The update to be applied.') | |
pprint(my_update) | |
update_dict(my_dict, my_update) | |
print('Updated dictionary with new keys and updated values.') | |
pprint(my_dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment