【问题标题】:How to add a subkey in a nested dictionary如何在嵌套字典中添加子键
【发布时间】:2021-11-23 18:32:22
【问题描述】:

所以我有一个类型列表: x= [('0', '0', '20'), ('0', '0', '25'),('0', '3', '28'), ('1', '1', '74'), ('1', '1', '2')]

我想通过迭代原始字典(而不是手动添加)来创建嵌套字典:

dictionary= {'0': {'0': ('20', '25')},{'3': ('28')} , '1': {'1': ('74 ', '2')}}

换句话说,在元组列表中,将它们分组:元组的第一个元素是键,第二个是子键,第三个是子键的值。

  • 如果两个元组具有相同的键和子键,我们将值添加到值中(即{'0':'0': ('20', '25')}
  • 如果他们有相同的key但不同的子key,我们在相同的key下添加一个子key,key对(即{'0':{'0': ('20', '25')},{'3 ': ('28')}}

代码会怎样?

【问题讨论】:

  • '0': {'0': ('20', '25')},{'3': ('28')} 正确吗?你要的是'0': { '0': ('20', '25'), '3': ('28') },不是吗?

标签: python loops dictionary nested nested-lists


【解决方案1】:

尝试以下方法:

x = [('0','0','20'),('0','0','25'),('0','3','28'),('1','1','74'),('1','1','2')]


from collections import defaultdict
your_dict = defaultdict(dict)

for row in x:
    your_dict[row[0]][row[1]] = tuple([n for n in [r[2] for r in x if r[1] == row[1]]])

您的准确预期输出:

{'0': {'0': ('20','25'), '3': ('28')}, '1': {'1': ('74','2')}})
    

【讨论】:

    【解决方案2】:
    x = [('0', '0', '20'), ('0', '0', '25'),('0', '3', '28'), ('1', '1', '74'), ('1', '1', '2')]
    
    a = {}
    
    def add_dict2(innerdict, ele2, ele3):
        if not innerdict.get(ele2):
            innerdict[ele2] = []
    
        innerdict[ele2].append(ele3)
    
    def add_dict(elel, ele2, ele3):
        if not a.get(ele1):
            a[ele1] = {}
    
        add_dict2(a[ele1], ele2, ele3)
    
    for (ele1, ele2, ele3) in x:
        add_dict(ele1, ele2, ele3)
    
    print(a)
    

    打印

    {'0': {'0': ['20', '25'], '3': ['28']}, '1': {'1': ['74', '2']}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-25
      • 2018-08-17
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2015-06-14
      • 2020-08-17
      • 2012-12-31
      相关资源
      最近更新 更多