Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将dict写入具有特定格式的文件_Python 3.x_Dictionary_Formatting_Output - Fatal编程技术网

Python 3.x 将dict写入具有特定格式的文件

Python 3.x 将dict写入具有特定格式的文件,python-3.x,dictionary,formatting,output,Python 3.x,Dictionary,Formatting,Output,如果我想用每行的特定格式将dict写入文件,那么最好的方法是什么 目前我正在做: with open('filename', 'w') as j: print(dct, file = j) 但正如你所期望的,我的结果是: {<key>: <value>, <key>: <value>, <key>: <value>} {:,:,:} 是否有一种简单的方法来格式化输出,使其读取与以下内容相

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

目前我正在做:

    with open('filename', 'w') as j:
        print(dct, file = j)
但正如你所期望的,我的结果是:

    {<key>: <value>, <key>: <value>, <key>: <value>}
{:,:,:}
是否有一种简单的方法来格式化输出,使其读取与以下内容相同的dict:

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

您可以按如下方式执行:

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对象没有属性iteritemswopse,在python 3中它只是