将包含元组列表的字典导出到CSV文件中

问题描述 投票:0回答:1

我想将以下字典导出到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

[如果可能,我想避免使用熊猫。有任何提示吗?

谢谢

python python-3.x export-to-csv
1个回答
0
投票

使用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)
© www.soinside.com 2019 - 2024. All rights reserved.