我想将dict写入csv作为这种形式:
(column1) (column2)
aaa 1
bbb 2
但是当我在下面的代码中使用'\ t'作为分隔符时:
import csv
csv_filename = "test.csv"
dict = {'aaa': 1, 'bbb': 2}
with open(csv_filename, 'wb') as f:
writer = csv.writer(f, delimiter='\t')
for key, value in dict.items():
writer.writerow([key, value])
我无法获得所需的输出,而是创建的csv就像
(column1) (column2)
aaa1
bbb2
答案 0 :(得分:4)
您正在将输出转换为组合键和值的列表。请改用以下内容。
import csv
csv_filename = "test.csv"
dict = {'aaa': 1, 'bbb': 2}
with open(csv_filename, 'wb') as f:
writer = csv.DictWriter(f, delimiter='\t')
writer.writerows(dict)