元组列表到词典

2024-05-19 17:06:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在以list of tuples的形式从分层数据库中检索(root, parent1, parent2, child1),如下所示:

[('HCS', 'Assured Build', 'Implementation', 'Hardware Stack'), 
('HCS', 'Assured Build', 'Implementation', 'SA and SF'),
('HCS', 'Assured Build', 'Testing and Validation', 'NFRU-SS'),
('HCS', 'Assured Build', 'Testing and Validation', 'NRFU-UC'), 
('HCS', 'Assured Platform', 'Restoration', 'AS Build'), 
('HCS', 'Assured Platform', 'Restoration', 'Capacity Management'),
('HCS', 'Assured Platform', 'Migration', 'Document Review')]

我想创建一个dictionary of dictionary,这样可以轻松迭代并创建树状视图:

{"HCS":
      {"Assured Build":
             {"Implementation":{"Hardware Stack", "Software"},
             {"Testing and Validation":{"NRFU-SS", "NRFU-UC"}
      },
      {"Assured Platform":
              {"Restoration":{"AS Build","Capacity Management"},
              {"Migration":{"Document Review"}},
      }

}

处理这个问题最好的方法是什么?我试过namedtuple和defaultdict,但都失败了。你知道吗


Tags: andofbuildstacktestingsshardwareimplementation
2条回答

您需要^{}defaultdictdefaultdictlist(或者set,如果需要的话):

import json
from collections import defaultdict

l = [('HCS', 'Assured Build', 'Implementation', 'Hardware Stack'),
     ('HCS', 'Assured Build', 'Implementation', 'SA and SF'),
     ('HCS', 'Assured Build', 'Testing and Validation', 'NFRU-SS'),
     ('HCS', 'Assured Build', 'Testing and Validation', 'NRFU-UC'),
     ('HCS', 'Assured Platform', 'Restoration', 'AS Build'),
     ('HCS', 'Assured Platform', 'Restoration', 'Capacity Management'),
     ('HCS', 'Assured Platform', 'Migration', 'Document Review')]

d = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
for key1, key2, key3, value in l:
    d[key1][key2][key3].append(value)

print(json.dumps(d, indent=4))

json.dumps()这里只是为了一个漂亮的印刷品。它打印:

{
    "HCS": {
        "Assured Platform": {
            "Restoration": [
                "AS Build",
                "Capacity Management"
            ],
            "Migration": [
                "Document Review"
            ]
        },
        "Assured Build": {
            "Implementation": [
                "Hardware Stack",
                "SA and SF"
            ],
            "Testing and Validation": [
                "NFRU-SS",
                "NRFU-UC"
            ]
        }
    }
}

我们还可以使嵌套的defauldict初始化步骤更通用一些extract that into a reusable method

def make_defaultdict(depth, data_structure):
    d = defaultdict(data_structure)
    for _ in range(depth):
        d = defaultdict(lambda d=d: d)
    return d

然后,您可以替换:

d = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))

使用:

d = make_defaultdict(2, list)

相关问题 更多 >