【问题标题】:Writing a dict to a file with a certain format将字典写入具有特定格式的文件
【发布时间】:2014-04-14 03:27:20
【问题描述】:

如果我想将 dict 写入每行具有特定格式的文件,那么最好的方法是什么?

目前我在做:

    with open('filename', 'w') as j:
        print(dct, file = j)

但正如你所料,我的输出是:

    {<key>: <value>, <key>: <value>, <key>: <value>}

是否有一种简单的方法来格式化输出,使其读取与以下相同的字典:

    <key> <value>
    <key> <value>
    <key> <value>

【问题讨论】:

    标签: python-3.x dictionary formatting output


    【解决方案1】:

    你可以这样做:

    def write_dict(out_dict, filename):
        with open(filename, 'w') as f:
            for key, value in out_dict.items():
                f.write('{} {}\n'.format(key, value))
    

    【讨论】:

    • 你不应该,它们都是内置的。但是您确实需要确保该文件实际上可以打开(即 python 的 open 实际上不会沿文件路径为您创建缺少的目录)
    • 它只是说dict对象没有属性iteritems
    • 哎呀,在 python 3 中它只是 items
    猜你喜欢
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多