将包含元组列表的词典导出到CSV-fi

2024-10-02 18:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如果可能的话,我想避免使用熊猫。 有什么提示吗

谢谢


Tags: 文件csv代码datadefwithresopen
1条回答
网友
1楼 · 发布于 2024-10-02 18:26:49

使用itertools.zip_longest

例如:

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)

相关问题 更多 >