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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25778021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:37:58  来源:igfitidea点击:

How can I save a list of dictionaries to a file?

pythonlistfiledictionary

提问by Python Novice

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?

我找到了有关如何将列表写入文件的答案,但这假定它是一个平面列表。我怎样才能用字典列表来做到这一点?

My list looks like this:

我的清单是这样的:

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"
    },
]

采纳答案by mgilson

provided that the object only contains objects that JSON can handle (lists, tuples, strings, dicts, numbers, None, Trueand False), you can dump it as json.dump:

只要该对象仅包含对象JSON可以处理(liststuplesstringsdictsnumbersNoneTrueFalse),你可以转储它那样json.dump

import json
with open('outputfile', 'w') as fout:
    json.dump(your_list_of_dict, fout)

回答by ppalacios

The way you will have to follow to write a dict to a file is kind different from the post you have mentioned.

您必须遵循的将 dict 写入文件的方式与您提到的帖子有所不同。

First, you need serialize the object and than you persist it. These are fancy names for "write python objects to a file".

首先,您需要序列化对象,然后将其持久化。这些是“将 python 对象写入文件”的奇特名称。

Python has 3 serialization modules included by default that you can use to achieve your objective. They are: pickle, shelve and json. Each one has its own characteristics and the one you have to use is the one which is more suitable to your project. You should check each module documentation to get more on it.

Python 默认包含 3 个序列化模块,您可以使用它们来实现目标。它们是:pickle、shelve 和 json。每一种都有自己的特点,您必须使用的一种是更适合您的项目的一种。您应该检查每个模块文档以获取更多信息。

If your data will be only be accessed by python code, you can use shelve, here is an example:

如果你的数据只能被python代码访问,你可以使用shelve,这是一个例子:

import shelve

my_dict = {"foo":"bar"}

# file to be used
shelf = shelve.open("filename.shlf")

# serializing
shelf["my_dict"] = my_dict

shelf.close() # you must close the shelve file!!!

To retrieve the data you can do:

要检索数据,您可以执行以下操作:

import shelve

shelf = shelve.open("filename.shlf") # the same filename that you used before, please
my_dict = shelf["my_dict"]
shelf.close()

See that you can treat the shelve object almost the same way you do with a dict.

请注意,您可以像处理 dict 一样处理搁置对象。

回答by Nikos Tavoularis

Just for completeness I add also the json.dumps()method:

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

with open('outputfile_2', 'w') as file:
    file.write(json.dumps(logic_steps, indent=4))

Have a look herefor the difference between json.dump()and json.dumps()

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

回答by Reihan_amn

if you want each dictionary in one line:

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

 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")