我有一个python dict,
D = {
'outermost': {
'inner': {
'key1': '',
'key2': '',
'key3': '',
'key4': '',
'key5': ''
}
}
}
列表,
L = ['outermost', 'inner']
和一个字符串,
K = 'key1'
和一个值,
V = 'add a value'
如何获得输出,就像这样
D = {
'outermost': {
'inner': {
'key1': 'add a value',
'key2': '',
'key3': '',
'key4': '',
'key5': ''
}
}
}
答案 0 :(得分:5)
使用reduce
和operator.getitem
:
from operator import getitem
reduce(getitem, L, D)[K] = V
<强>输出:强>
>>> from pprint import pprint
>>> pprint(D)
{'outermost': {'inner': {'key1': 'add a value',
'key2': '',
'key3': '',
'key4': '',
'key5': ''}}}
答案 1 :(得分:1)
像这样:
# 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)