【问题标题】:write a dictionary of different-length lists to a csv file将不同长度列表的字典写入 csv 文件
【发布时间】:2015-09-09 22:02:30
【问题描述】:

我正在尝试将列表字典写入 csv 文件。解决方法在:Write dictionary of lists to a CSV file

将修剪较长的列表。例如,如果我想写以下内容:

d = {"key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9, 11]}
with open("test.csv", "wb") as outfile:
writer = csv.writer(outfile)
writer.writerow(d.keys())
writer.writerows(zip(*d.values()))

结果是

key3   key2  key1
7      4     1
8      5    2
9      6    3

11 从 key3 中删除。有什么想法吗?

【问题讨论】:

  • 使用循环而不是 writerows+zip
  • 我试过了,但没有得到我想要的。

标签: python-2.7


【解决方案1】:

快速简单的答案是使用itertools.izip_longest 而不是zip

import itertools
import csv

d = {"key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9, 11]}
with open("test.csv", "wb") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(d.keys())
    writer.writerows(itertools.izip_longest(*d.values()))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 2014-06-17
    • 2017-06-24
    相关资源
    最近更新 更多