【问题标题】:Save unbalanced dictionary in txt file将不平衡的字典保存在 txt 文件中
【发布时间】:2015-11-03 13:18:14
【问题描述】:

我需要在 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)

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

【问题讨论】:

    标签: python file dictionary encoding utf-8


    【解决方案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)))
    

    【讨论】:

      【解决方案2】:

      你也可以试试:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        • 1970-01-01
        • 2017-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多