我有一本字典,其中包含以下内容:
{'Jim': ['1', '9', '5'], 'kim': ['8', '6', '0'], 'lim': ['10', '6', '1'], 'slim': ['8', '8', '2'], 'pimp': ['9', '9', '1'], 'sim': ['8', '7', '1']}
我的问题是:我如何将所有这些写入CSV文件?
它应该在CSV文件中编写并显示如下内容:
name x y z
name2 x y z
名称3 x y z
...
我试过了:
with open('file.csv', 'wb') as csvfile:
wr = csv.writer(csvfile)
wr.writerow(DICTIONARY)
答案 0 :(得分:0)
您可以迭代字典项并一次写一行:
import csv
D = {'Jim': ['1', '9', '5'], 'kim': ['8', '6', '0'], 'lim': ['10', '6', '1'],
'slim': ['8', '8', '2'], 'pimp': ['9', '9', '1'], 'sim': ['8', '7', '1']}
with open('file.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for name, items in D.items():
writer.writerow([name] + items)
检查csv.writer
文档here
请注意,Python字典是无序的,即每次运行时可能不会生成相同的文件。
答案 1 :(得分:0)
下面的代码将列表列表分成不同的列(通过编辑eugene'代码完成)
with open("file.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for name, items in DICTIONARY.items():
writer.writerow([name] + items)