user3351750 user3351750 - 1 year ago 75
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
is there a way to add an entry in the dict

Expected Result:

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download