Translate a table to a hierarchical dictionary?(将表转换为分层字典?)
问题描述
我有一个表格:
A1, B1, C1, (value)
A1, B1, C1, (value)
A1, B1, C2, (value)
A1, B2, C1, (value)
A1, B2, C1, (value)
A1, B2, C2, (value)
A1, B2, C2, (value)
A2, B1, C1, (value)
A2, B1, C1, (value)
A2, B1, C2, (value)
A2, B1, C2, (value)
A2, B2, C1, (value)
A2, B2, C1, (value)
A2, B2, C2, (value)
A2, B2, C2, (value)
我想在 python 中使用它作为字典,形式:
I'd like to work with it in python as a dictionary, of form:
H = {
'A1':{
'B1':{
'C1':[],'C2':[],'C3':[] },
'B2':{
'C1':[],'C2':[],'C3':[] },
'B3':{
'C1':[],'C2':[],'C3':[] }
},
'A2':{
'B1':{
'C1':[],'C2':[],'C3':[] },
'B2':{
'C1':[],'C2':[],'C3':[] },
'B3':{
'C1':[],'C2':[],'C3':[] }
}
}
这样 H[A][B][C]
会产生一个特定的唯一值列表.对于小型字典,我可能只是像上面那样预先定义结构,但我正在寻找一种有效的方法来迭代表并构建字典,而无需提前指定字典键.
So that H[A][B][C]
yields a particular unique list of values. For small dictionaries, I might just define the structure in advance as above, but I am looking for an efficient way to iterate over the table and build a dictionary, without specifying the dictionary keys ahead of time.
推荐答案
input = [('A1', 'B1', 'C1', 'Value'), (...)]
from collections import defaultdict
tree = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
#Alternatively you could use partial() rather than lambda:
#tree = defaultdict(partial(defaultdict, partial(defaultdict, list)))
for x, y, z, value in input:
tree[x][y][z].append(value)
这篇关于将表转换为分层字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!