Reputation: 8886
I have a python dict,
D = {
'outermost': {
'inner': {
'key1': '',
'key2': '',
'key3': '',
'key4': '',
'key5': ''
}
}
}
a list,
L = ['outermost', 'inner']
and a string,
K = 'key1'
and a value,
V = 'add a value'
How can I get a output like this
D = {
'outermost': {
'inner': {
'key1': 'add a value',
'key2': '',
'key3': '',
'key4': '',
'key5': ''
}
}
}
Upvotes: 2
Views: 124
Reputation: 24788
Like this:
# Will raise a KeyError if the path does not exist.
def set_dict_path(dct, path, key, value):
for p in path:
dct = dct[p]
dct[key] = value
set_dict_path(D, L, K, V)
Upvotes: 1
Reputation: 250931
Using reduce
and operator.getitem
:
from operator import getitem
reduce(getitem, L, D)[K] = V
Output:
>>> from pprint import pprint
>>> pprint(D)
{'outermost': {'inner': {'key1': 'add a value',
'key2': '',
'key3': '',
'key4': '',
'key5': ''}}}
Upvotes: 5