如何将字典列表保存到文件中? [英] How can I save a list of dictionaries to a file?
问题描述
我有一个字典列表.有时,我想更改并保存这些词典之一,以便在重新启动脚本时利用新消息.现在,我通过修改脚本并重新运行来进行更改.我想将其从脚本中删除,并将字典列表放入某种配置文件中.
I have a list of dictionaries. Occasionally, I want to change and save one of these dictionaries so that the new message is utilized if the script is restarted. Right now, I make that change by modifying the script and rerunning it. I'd like to pull this out of the script and put the list of dictionaries into a configuration file of some kind.
我找到了有关如何将列表写入文件的答案,但这假定它是一个平面列表.如何使用词典列表呢?
I've found answers on how to write a list to a file, but this assumes that it is a flat list. How can I do it with a list of dictionaries?
我的列表如下:
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"
},
]
推荐答案
假定该对象仅包含JSON可以处理的对象(lists
,tuples
,strings
,dicts
,numbers
,None
,True
和False
),则可以将其转储为 json.dump :
provided that the object only contains objects that JSON can handle (lists
, tuples
, strings
, dicts
, numbers
, None
, True
and False
), you can dump it as json.dump:
import json
with open('outputfile', 'w') as fout:
json.dump(your_list_of_dict, fout)
这篇关于如何将字典列表保存到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!