【问题标题】:How to add values dynamically to nested dicts?如何动态地将值添加到嵌套字典?
【发布时间】: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


【解决方案1】:

你可以的

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)

【讨论】:

    【解决方案2】:

    您可以遍历键直到到达最里面的字典,然后设置值:

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

    【讨论】:

      【解决方案3】:

      这是一种递归方式:

      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'}}}}
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          【解决方案5】:

          您可以使用 for 循环在字典中找到 None 并输入新键。

          会是这样的:

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

          【讨论】:

            猜你喜欢
            • 2023-01-22
            • 1970-01-01
            • 2021-01-26
            • 2015-07-27
            • 2019-02-14
            • 1970-01-01
            • 2020-05-29
            • 1970-01-01
            • 2020-08-11
            相关资源
            最近更新 更多