Created
October 2, 2019 17:09
-
-
Save svidgen/a3b13d0a8dcc8995810b91ebc4d3603e to your computer and use it in GitHub Desktop.
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
from copy import deepcopy | |
def insert_dict_leaves(source, additions): | |
rv = deepcopy(source) | |
for k, v in additions.items(): | |
if not (k in rv and isinstance(rv[k], dict)): | |
rv[k] = v | |
elif isinstance(v, dict): | |
rv[k] = insert_dict_leaves(rv[k], v) | |
else: | |
rv[k] = v | |
return rv | |
source_dict = { | |
'untouched_scalar': 'untouched value', | |
'untouched_dict': { | |
'subkey': 'subkey value' | |
}, | |
'touched_scalar': 'not yet touched value', | |
'touched_dict': { | |
'subkey 1': 'subkey 1 value' | |
} | |
} | |
additions_dict = { | |
'touched_scalar': 'rewritten value', | |
'touched_dict': { | |
'subkey 2': 'subkey 2 value' | |
} | |
} | |
from pprint import pprint | |
pprint(insert_leaves(source_dict, additions_dict)) | |
{'touched_dict': {'subkey 1': 'subkey 1 value', 'subkey 2': 'subkey 2 value'}, | |
'touched_scalar': 'rewritten value', | |
'untouched_dict': {'subkey': 'subkey value'}, | |
'untouched_scalar': 'untouched value'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment