2015-11-03 43 views
0

我需要在txt文件中導出不平衡字典。該字典包含必須保留的UTF-8字符。這個例子是如下:保存txt文件中的不平衡字典

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) 

但它不工作時所有鍵的值數量都不相同。有人有答案嗎? 在此先感謝。

回答

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))) 
0

你還可以嘗試:

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