我的数据结构如下:
[(a,x1,1),(a,x2,5),(b,x1,1) ...]
我想把它变成一个嵌套的字典
{a:{x1:1, x2:5}, b:{x1:1}...}
我试过了
dictdata = {}
for row in rows:
ean = row[1].encode('ascii','ignore')
period = str(row[0])
value = row[2]
dictdata[ean]={} # init sub dictionary
dictdata[ean][period] = value
但每次我执行 dictdata[ean]={} 时,内容都会被删除,所以这行不通。如果我不初始化子词典,我也无法让它工作。
感谢任何帮助
请您参考如下方法:
这就是 collections.defaultdict 旨在解决的问题:
https://docs.python.org/2/library/collections.html#collections.defaultdict
from collections import defaultdict
dictdata = defaultdict(dict)
rows = [('a','x1',1),('a','x2',5),('b','x1',1) ]
for row in rows:
ean = row[1].encode('ascii','ignore')
period = str(row[0])
value = row[2]
dictdata[period][ean] = value
dictdata
返回
{'a': {'x2': 5, 'x1': 1}, 'b': {'x1': 1}}
