在txt文件中保存不平衡字典

时间:2015-11-03 13:18:15

标签: python file dictionary encoding utf-8

我需要在txt文件中导出不平衡字典。字典包含必须保留的UTF-8字符。示例如下:

dict = {"Polić":("a","c","e"), "Batman":("b","d")}

最后,我需要以下文本文件:

"Polić","a","c","e"
"Batman","b","d"

我尝试了以下代码

with open("my/File.txt", "w",encoding='utf-8') as file:
    for p in dict.items(): 
        file.writelines("%s:%s\n" % p)

但是当所有键的值数量不同时,它不起作用。有人有答案吗? 提前致谢。

2 个答案:

答案 0 :(得分:1)

以下应该可以正常工作:

my_dict = {"Polic":("a","c","e"), "Batman":("b","d")}

with open("my/File.txt", "w", encoding='utf-8') as file:
    for k,v in my_dict.items(): 
        file.write('"{}","{}"\n'.format(k, '","'.join(v)))

答案 1 :(得分:0)

您也可以尝试:

with open('my_file.txt', 'w') as f:
    [f.write('{0},{1}\n'.format(key, value)) for key, value in my_dict.items()]