python - 将数据从字典加载到 csv

标签 python csv dictionary text

我有一本这种格式的字典:

data_dict = {'a' : [1,2,3], 'b' : [[4,5],[6,7],[8,9]]}

我想做的是将字典中的数据解析为“格式”列中的 csv 文件。所以 key 是一个标题,然后是 values,所以输出应该是这样的:

a    b
1    [4,5]
2    [6,7]
3    [8,9]

我尝试过使用 csv.DictWritercsv.writer 但没有任何效果。

最佳答案

您可以使用 zip聚合来自多个可迭代对象的元素:

>>> rows = zip([1,2,3], [[4,5],[6,7],[8,9]])
>>> for row in rows:
...     print(row)
...
(1, [4, 5])
(2, [6, 7])
(3, [8, 9])

import csv
import sys

data_dict = {'a' : [1,2,3], 'b' : [[4,5],[6,7],[8,9]]}    
keys = sorted(data_dict)  # to get ordered keys
values = [data_dict[key] for key in keys]

writer = csv.writer(sys.stdout, delimiter='\t')  # Replace `sys.stdout` as you need
writer.writerow(keys)
for row in zip(*values):
    writer.writerow(row)

关于python - 将数据从字典加载到 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42454080/

相关文章:

python - 将多个参数从 bash 传递到 python

Python Pandas 处理 308 请求

python - Pandas 数据框图

python - 使用来自另一个数据框的匹配值列表创建数据框列

powershell - 在 Register-ObjectEvent 中使用格式表

c# - C# 中动态字典的使用

python - 从字典中读取字典

python - 如何递归地jsonize python对象

python - 无法找到模块,即使它已安装并且可以运行

java - 打开导出的 CSV 文件时,Excel 不显示小数点零