from collections import defaultdict
dic = defaultdict(list)
for......
dic['XYZ'].append(val) #At the end of your for loop dic = {ABCD: [1,2,3,4], EFGH: [5,6,2,4,8]....}
rows = dic.values()
rows = zip(*rows) #Both CSV and zip don't support variable length lines, so make all arrays of equal length by padding zeroes to the end before this line
with open('filename.csv','wb') as fp:
fieldnames = dic.keys()
writer = csv.writer(fp)
writer.writerow(fieldnames)
writer.writerows(rows)
我觉得这个设计有点刺耳。你在字典里只使用一个键有什么特别的原因吗?您可以做的是保留一个字典,其中每个值都是该特定键的元素列表。所以你的代码看起来像这样:
相关问题 更多 >
编程相关推荐