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

45 投票
5 回答
97107 浏览
提问于 2025-04-21 00:22

我有一个字典的列表。有时候,我想要修改并保存其中一个字典,这样如果脚本重新启动时,就能使用到新的信息。目前,我是通过修改脚本并重新运行来实现这个修改的。我希望能把这个过程从脚本中抽离出来,把字典列表放到某种配置文件里。

我找到了一些关于如何把列表写入文件的答案,但那些答案都是针对简单的列表。那我该如何处理字典列表呢?

我的列表看起来是这样的:

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

5 个回答

0

这个问题的被接受的答案对这个问题也非常有效。它不是使用json,而是用pickle来处理数据的存储,这样做可以更方便地管理数据,即使是处理字典列表的情况也没问题:

import pickle

list_of_dicts = [{'a': 1, 'b': 2}, {'aa': 2, 'bb': 3}]

with open('saved_list.pkl', 'wb') as f:
    pickle.dump(list_of_dicts, f)
        
with open('saved_list.pkl', 'rb') as f:
    loaded_list_of_dicts = pickle.load(f)
3

要把一个字典写入文件,其实有点不同于你提到的那种方法。

首先,你需要把这个对象“序列化”,然后再保存它。这些听起来很复杂的词,其实就是“把Python对象写入文件”的意思。

Python默认提供了三个序列化模块,你可以用它们来实现这个目标。它们分别是:pickle、shelve和json。每个模块都有自己的特点,你需要选择最适合你项目的那个。建议你查看每个模块的文档,了解更多信息。

如果你的数据只会被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!!!

要取回数据,你可以这样做:

import shelve

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

注意,你可以把shelve对象几乎和字典一样使用。

7

为了完整性,我也加上了 json.dumps() 这个方法:

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

想了解 json.dump()json.dumps() 之间的区别,可以查看 这里

20

如果你想让每个字典都在一行显示:

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

只要这个对象里面只包含 JSON 能处理的东西,比如 列表元组字符串字典数字NoneTrueFalse,你就可以用 json.dump 来把它保存成 JSON 格式:

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

撰写回答