user3351750 user3351750 - 3 months ago 10
Python Question

adding value to dict using keys list

Consider the scenario in which list contains key of a dict

x = {'a':{'b': 1}}
lst = ['a','c']
value = {'d': 3}


Using the keys present in the list
lst
is there a way to add an entry in the dict
x
.

Expected Result:

x = {'a': {'c': {'d': 3}, 'b': 1}}

Answer

Use a loop an a temporary dictionary_variable:

tmp_dict = x
for key in lst[:-1]:
    tmp_dict = tmp_dict[key]
tmp_dict[lst[-1]] = value
print x

Notice, that the loop over all keys except the last one, since we need the last key for the assignment operation.