I would like to export the following dictionary to csv file:
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:
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. Any hints?
Thanks
Use 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.