【发布时间】:2020-10-14 20:54:11
【问题描述】:
我想为嵌套字典中的特定键添加一个值,我不知道如何才能做到这一点。所以我有一个:
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?当然thedict和thelist是动态创建的,我也不能这样:
thedict[thelist[0]][thelist[1]][thelist[2]][thelist[3]] = thevalue
【问题讨论】:
-
为了确保我理解这个问题 - 您想使用“theList”中的项目作为“theDict”中相关位置的路径吗?
-
您只想向第四个条目添加值,还是想要一个通用的答案,允许您向字典的任何位置添加新值?
-
在我看来,您想要创建一个可以通过名称增长和访问的树状结构。对吗?
标签: python dictionary nested