gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:49:29 24 4
gpt4 key购买 nike

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

关于python - 将字典写入文件(CSV 或 TSV),其中键是多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com