我想将以下字典导出到csv文件:
res_dict = {'A':[(0.1,5),(0.2,6)],'B':[(0.1,3),(0.2,6),(0.6,8),(0.7,9)]}
我尝试了以下代码:
def exportDataToCSV(res):
with open('XY-data.csv', "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(res.keys())
for v in res.values():
writer.writerows(zip(*v))
问题是,我仍然必须转置excel工作表中的数据以具有所需的视图,如下所示:
col1 col2 col3 col4
A B
0.1 5 0.1 3
0.2 6 0.2 6
0.6 8 0.7 9
[如果可能,我想避免使用熊猫。有任何提示吗?
谢谢
使用itertools.zip_longest
Ex:
import csv
from itertools import zip_longest
res_dict = {'A':[(0.1,5),(0.2,6)],'B':[(0.1,3),(0.2,6),(0.6,8),(0.7,9)]}
def exportDataToCSV(res):
with open('XY-data.csv', "w") as outfile:
writer = csv.writer(outfile)
writer.writerow(res.keys())
for v in zip_longest(*res.values(), fillvalue=''):
values = [",".join(map(str,i)) for i in v]
writer.writerow(values)
exportDataToCSV(res_dict)