[英]Export a dictionary containing list of tuples to CSV file
I would like to export the following dictionary to csv file:我想将以下字典导出到 csv 文件:
res_dict = {'A':[(0.1,5),(0.2,6)],'B':[(0.1,3),(0.2,6),(0.6,8),(0.7,9)]
I tried the following code:我尝试了以下代码:
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))
The problem is, that still I must transpose the data in excel sheet to have required view, as follows:问题是,我仍然必须将 excel 表中的数据转置以获得所需的视图,如下所示:
A B
0.1,5 0.1,3
0.2,6 0.2,6
0.6,8
0.7,9
If possible I would like to avoid using pandas.如果可能的话,我想避免使用 pandas。 Any hints?有什么提示吗?
Thanks谢谢
Use itertools.zip_longest
使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.