将字典写入文件(CSV 或 TSV),其中键是多个项目

Write dictionary to file (CSV or TSV) where key is multiple items

当我的数据如下所示(键中有多个项目)时,如何将字典写入 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")

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

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

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')]}