【问题标题】:Write dictionary to file (CSV or TSV) where key is multiple items将字典写入文件(CSV 或 TSV),其中键是多个项目
【发布时间】:2016-03-14 23:26:32
【问题描述】:

当我的数据看起来像这样(键中有多个项目)时,我如何将字典写入 CSV 或 TSV:

defaultdict(<type 'list'>, {('1_719263', 35, 4): [(1, 1, 'KEEP')]})

其中键是('1_713', 35, 4),值是[(1, 1, 'KEEP')]

我想使用json 甚至csv.writer

我也试过这个:

with open (output_name, "a") as f:
    f.write(first_line + "\n")
    for key, value in x_y_output.iteritems():
        f.write(str((key, value)) + "\n")

但这不起作用,我无法摆脱()[]{}等。

【问题讨论】:

  • 您的示例字典是否缺少结束 '}'?

标签: python file csv defaultdict


【解决方案1】:

您可以尝试将输出字符串格式化为制表符分隔的行:

with open (output_name, "a") as f:
    f.write(first_line + "\n")
    for key, value in my_dict.items():
        f.write("{}\t{}\n".format(key, value))

然后在读取数据时,您可以使用以下方法对其进行重构:

new_dict = {}
with open (output_name, "r") as f:
    for line in f:
        inline_list = line.rstrip.split('\t')
        new_dict[eval(inline_list[0])] = eval(inline_list[1])

python shell 中的示例:

>>> src_dict
{('1_719263', 35, 4): [(1, 1, 'KEEP')]}
>>> for key, value in d.items():
...     outstring = "{}\t{}\n".format(k,v)
...     # write to file
... 
>>> outstring
"('1_719263', 35, 4)\t[(1, 1, 'KEEP')]\n"
>>> instring = outstring.rstrip().split('\t')
>>> instring
["('1_719263', 35, 4)", "[(1, 1, 'KEEP')]"]
>>> new_dict = {}
>>> new_dict[eval(instring[0])] = eval(instring[1])
>>> new_dict
{('1_719263', 35, 4): [(1, 1, 'KEEP')]}

【讨论】:

    猜你喜欢
    • 2017-12-12
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2012-01-30
    • 2021-06-15
    • 2023-03-03
    • 2018-04-08
    相关资源
    最近更新 更多