如何动态地将值添加到嵌套字典?

时间:2020-06-24 14:44:19

标签: python dictionary nested

我想为嵌套字典中的特定键添加一个值,我不知道如何实现这一点。所以我有一个:

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分配给four?当然,thedictthelist是动态创建的,我不能只是这样做:

thedict[thelist[0]][thelist[1]][thelist[2]][thelist[3]] = thevalue

5 个答案:

答案 0 :(得分:2)

你可以做

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)

答案 1 :(得分:0)

您可以循环浏览按键,直到到达最里面的字典,然后设置值:

# Loop until inner dict
subdict = thedict
for key in thelist[:-1]:
    subdict = subdict.get(key)

# Set value
subdict[thelist[-1]] = thevalue

答案 2 :(得分:0)

这是一种递归的方法:

 err : Error: soapenv:Server: error: The document is not a getAuthorizationRequest@http://www.xyzabcdefgh.com/auth/operations/2009/3: document element mismatch got getAuthorizationRequestMsg

答案 3 :(得分:0)

我似乎想创建一个tree,可以通过路径访问它并保存值。在这种情况下,树的每个节点必须能够保存一个值和一个分支。但是,这意味着您需要的结构与现在的结构略有不同。

答案 4 :(得分:-2)

您可以使用for循环在字典中找到“无”并放置新密钥。

会是这样的:

for key, value in thedict.values():
    if value is None:
        thedict[key] = new_dict