本文介绍了将表格翻译成分层字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张表格,其形式为:
I have a table of the form:
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)
这篇关于将表格翻译成分层字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!