我有以下字典
dict = {5: [ [a00, a01, ..., a0n], [a10, a11, ..., a1n], ... ],
6: [ [b00, b01, ..., b0n], [b10, b11, ..., b1n], ... ],
7: [ [c00, c01, ..., c0n], [c10, c11, ..., c1n], ... ],
8: etcetera }
所有2d列表的列数相同,但行数不同。
将其写入csv文件的最佳方法是什么。我目前使用
w = csv.writer(open("python_output.csv", "w"))
for key, val in dict.items():
w.writerow([key, val])
但这不起作用,因为整个2d列表都放在CSV文件的一个单元格中。
答案 0 :(得分:1)
Itertools是你的朋友:
import itertools
w = csv.writer(open("python_output.csv", "w"))
for key, val in idict.items():
w.writerow([key, *itertools.chain(*val)])
输出文件的内容为:
5,a00,a01,a0n,a10,a11,a1n
6,b00,b01,b0n,b10,b11,b1n
7,c00,c01,c0n,c10,c11,c1n
答案 1 :(得分:1)
您可以使用writerows
可用的csv.writer
方法
import csv
dict1 = {5: [['a00', 'a01', 'a0n'], ['a10', 'a11', 'a1n'], ['a20', 'a21', 'a2n']], 6: [['b00', 'b01', 'b0n'], ['b10', 'b11', 'b1n'], ['b20', 'b21', 'b2n']], 7: [['c00', 'c01', 'c0n'], ['c10', 'c11', 'c1n'], ['c20', 'c21', 'c2n']], 8: [['d00', 'd01', 'd0n'], ['d10', 'd11', 'd1n'], ['d20', 'd21', 'd2n']]}
rows = [[k]+l for k,v in dict1.items() for l in v]
with open('tmp.txt', 'w') as f:
writer = csv.writer(f)
writer.writerows(rows)
输出
5,a00,a01,a0n
5,a10,a11,a1n
5,a20,a21,a2n
6,b00,b01,b0n
6,b10,b11,b1n
6,b20,b21,b2n
7,c00,c01,c0n
7,c10,c11,c1n
7,c20,c21,c2n
8,d00,d01,d0n
8,d10,d11,d1n
8,d20,d21,d2n