我正在(root, parent1, parent2, child1)
从分层数据库中以list of tuples
as的形式检索:
[('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失败。
您需要以下defaultdict
项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)))
和:
d = make_defaultdict(2, list)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句