Reputation: 927
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}}
Upvotes: 1
Views: 79
Reputation: 5126
Philipp's answer is good.
But here is my attempt to give you the exact answer you expected.
x = {'a':{'b' : 1}}
lst=['a','c']
value = {'d':3}
x[lst[0]][lst[1]] = value
print(x)
>> {'a': {'c': {'d': 3}, 'b': 1}}
Upvotes: 2
Reputation: 3565
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.
Upvotes: 1