如何将字典列表保存到文件中? [英] How can I save a list of dictionaries to a file?

查看:671
本文介绍了如何将字典列表保存到文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表.有时,我想更改并保存这些词典之一,以便在重新启动脚本时利用新消息.现在,我通过修改脚本并重新运行来进行更改.我想将其从脚本中删除,并将字典列表放入某种配置文件中.

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可以处理的对象(liststuplesstringsdictsnumbersNoneTrueFalse),则可以将其转储为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆