我想给嵌套的dict中的一个特定键添加一个值,我不知道如何才能做到这一点。 所以我有一个:
thedict = {'one': {'two': {'three': {'four': None}}}}
并且我想在four
中添加一个值,或者在one
中添加另一个键/值对:
thedict['one']['two']['three']['four'] = thevalue
thedict['one']['new'] = 'something else'
那是有可能的。 但是我怎样才能让这个更有活力呢? 例如,我在这个上下文中有一个列表:
thedict = {'one': {'two': {'three': {'four': None}}}}
thelist = ['one', 'two', 'three', 'four']
thevalue = 'something'
然后如何将thevalue
分配给foure
? 当然,thedict
和theList
是动态创建的,我不能只做:
thedict[thelist[0]][thelist[1]][thelist[2]][thelist[3]] = thevalue
您可以循环遍历这些键,直到到达最里面的dict,然后设置值:
# Loop until inner dict
subdict = thedict
for key in thelist[:-1]:
subdict = subdict.get(key)
# Set value
subdict[thelist[-1]] = thevalue
你能做的
thedict = {'one': {'two': {'three': {'four': None}}}}
thelist = ['one', 'two', 'three', 'four']
thevalue = 'something'
curr = thedict
for idx, k in enumerate(thelist):
if idx == len(thelist) - 1:
curr[k] = thevalue
else:
curr = curr[k]
print(thedict)
下面是一种递归的方法:
import pprint
thedict = {'one': {'two': {'three': {'four': None}}}}
thelist = ['one', 'two', 'three', 'four']
thevalue = 'something'
def assign_by_path(d, l, v):
if len(l) == 1:
d[l[0]] = v
else:
assign_by_path(d[l[0]], l[1:], v)
pprint.pprint(thedict)
==> {'one': {'two': {'three': {'four': None}}}}
assign_by_path(thedict, thelist, thevalue)
pprint.pprint(thedict)
==> {'one': {'two': {'three': {'four': 'something'}}}}