字典列表到词典

时间:2016-05-21 13:28:26

标签: python dictionary tree

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

[('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')]

我想创建一个字典字典,以便轻松迭代并创建树视图:

{"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失败。

1 个答案:

答案 0 :(得分:8)

您需要defaultdict defaultdict list 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这里仅供参考。它打印:

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))) 初始化步骤更加泛型defaultdict

d = make_defaultdict(2, list)

然后,您可以替换:

{{1}}

使用:

{{1}}