如何将列表字典写入csv文件? [英] How to write a dictionary of lists to a csv file?
问题描述
我有这个清单的字典,我想将它写到CSV文件中:
I have this dictionary of lists that I want to write it in a CSV file:
file2_Dict = {'id': ' ', 'gender': ['M', 'M'], 'name': ['Smith', 'John'], 'city': ['Omaha','Lincoln']}
问题在于,并非字典的所有键都具有作为值的项目列表.在这种情况下,键(即'id'
)具有一个字符串作为值(即" "
).我尝试使用 Tim Pietzcker 提供的解决方案,但是这样只会输出csv文件的标题(字典的键),如下所示:
The problem is that not all the keys of the dictionary have a list of items as a value. In this case the key (i.e.'id'
) has a string as value (i.e. " "
). I tried to use the solution provided by Tim Pietzcker, but this only outputs the header of the csv file (keys of the dictionary), like this:
id, gender, name, city
预期输出应为:
id, gender, name, city
,M,Smith,Omaha
,M,John,Lincoln
有什么办法解决这个问题吗?
Any idea how to solve this problem?
推荐答案
您可以对字典进行预处理,并将空"值替换为空列表.然后使用 itertools.izip_longest()
代替zip()
:>
You can pre-process the dictionary and replace "empty" values with empty lists. Then use itertools.izip_longest()
instead of zip()
:
import csv
from itertools import izip_longest
file2_Dict = {'id': ' ', 'gender': ['M', 'M'], 'name': ['Smith', 'John'], 'city': ['Omaha','Lincoln']}
# replace space string values with empty lists
for key, value in file2_Dict.items():
if value == ' ':
file2_Dict[key] = []
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(file2_Dict.keys())
writer.writerows(izip_longest(*file2_Dict.values()))
哪个会产生:
gender,city,id,name
M,Omaha,,Smith
M,Lincoln,,John
这篇关于如何将列表字典写入csv文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!