如何将字典列表保存到文件中?

Pyt*_*ice 16 python dictionary file list

我有一个词典列表.有时,我想更改并保存其中一个词典,以便在重新启动脚本时使用新消息.现在,我通过修改脚本并重新运行来进行更改.我想把它从脚本中拉出来并将字典列表放到某种配置文件中.

我已经找到了如何将列表写入文件的答案,但这假设它是一个平面列表.我怎么能用词典列表呢?

我的列表看起来像这样:

logic_steps = [
    {
        'pattern': "asdfghjkl",
        'message': "This is not possible"
    },
    {
        'pattern': "anotherpatterntomatch",
        'message': "The parameter provided application is invalid"
    },
    {
        'pattern': "athirdpatterntomatch",
        'message': "Expected value for debugging"
    },
]
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 32

提供的对象只包含JSON可处理(对象lists,tuples,strings,dicts,numbers,None,TrueFalse),你可以转储它那样json.dump:

import json
with open('outputfile', 'w') as fout:
    json.dump(your_list_of_dict, fout)
Run Code Online (Sandbox Code Playgroud)

  • 我收到错误TypeError:-0.69429028不是JSON可序列化的 (2认同)

Rei*_*amn 13

如果您希望将每个字典放在一行中:

 import json
 output_file = open(dest_file, 'w', encoding='utf-8')
 for dic in dic_list:
    json.dump(dic, output_file) 
    output_file.write("\n")
Run Code Online (Sandbox Code Playgroud)


Nik*_*ris 7

为了完整起见,我还添加了该json.dumps()方法:

with open('outputfile_2', 'w') as file:
    file.write(json.dumps(logic_steps, indent=4))
Run Code Online (Sandbox Code Playgroud)

看看这里json.dump()和之间的区别json.dumps()