存储 Python 字典
- 2025-01-15 08:45:00
- admin 原创
- 118
问题描述:
是否有简单的方法将字典(或多个字典)存储在例如 JSON 或pickle文件中?
例如,如果我有一些如下数据:
data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"
我如何将其保存在文件中,然后稍后从文件中将其加载回程序中?
JSON 和 Pickle 还可用于存储更复杂的结构化数据。此问题还可能包括针对上述简单字典情况的答案。有关更通用的方法,请参阅如何将结构化数据写入文件,然后稍后将其读回相同的结构?。请注意,将数据转换为可存储数据的技术称为序列化,重新创建数据结构称为反序列化;存储数据以供以后使用称为持久性。
另请参阅文件实际上包含什么,它们如何“读取”?什么是“格式”以及我为什么要担心它们?了解一些关于文件如何工作的理论,以及为什么结构化数据不能直接写入文件和从文件中读取。
解决方案 1:
泡菜保存:
try:
import cPickle as pickle
except ImportError: # Python 3.x
import pickle
with open('data.p', 'wb') as fp:
pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)
有关该参数的更多信息,请参阅pickle 模块文档protocol
。
腌制负荷:
with open('data.p', 'rb') as fp:
data = pickle.load(fp)
JSON保存:
import json
with open('data.json', 'w') as fp:
json.dump(data, fp)
提供额外的参数,例如sort_keys
或indent
,以获得漂亮的结果。参数sort_keys将按字母顺序对键进行排序,而indent将使用空格缩进数据结构indent=N
。
json.dump(data, fp, sort_keys=True, indent=4)
JSON加载:
with open('data.json', 'r') as fp:
data = json.load(fp)
解决方案 2:
最小示例,直接写入文件:
import json
json.dump(data, open(filename, 'wb'))
data = json.load(open(filename))
或安全打开/关闭:
import json
with open(filename, 'wb') as outfile:
json.dump(data, outfile)
with open(filename) as infile:
data = json.load(infile)
如果您想将其保存在字符串而不是文件中:
import json
json_str = json.dumps(data)
data = json.loads(json_str)
解决方案 3:
另请参阅加速包ujson:
import ujson
with open('data.json', 'wb') as fp:
ujson.dump(data, fp)
解决方案 4:
要写入文件:
import json
myfile.write(json.dumps(mydict))
要读取文件:
import json
mydict = json.loads(myfile.read())
myfile
是存储字典的文件的文件对象。
解决方案 5:
pickle
如果您想要或的替代方案json
,您可以使用klepto
。
>>> init = {'y': 2, 'x': 1, 'z': 3}
>>> import klepto
>>> cache = klepto.archives.file_archive('memo', init, serialized=False)
>>> cache
{'y': 2, 'x': 1, 'z': 3}
>>>
>>> # dump dictionary to the file 'memo.py'
>>> cache.dump()
>>>
>>> # import from 'memo.py'
>>> from memo import memo
>>> print memo
{'y': 2, 'x': 1, 'z': 3}
使用时klepto
,如果您使用serialized=True
,那么字典将会被写入memo.pkl
腌制字典而不是明文。
你可以从klepto
这里获取: https: //github.com/uqfoundation/klepto
dill
可能是比其本身更好的 pickling 选择pickle
,因为它dill
可以序列化 python 中的几乎任何东西。 klepto
也可以使用dill
。
你可以从dill
这里获取: https: //github.com/uqfoundation/dill
前几行额外的胡言乱语是因为klepto
可以配置为将字典存储到文件、目录上下文或 SQL 数据库中。无论您选择哪种后端存档,API 都是相同的。它为您提供了一个“可存档”字典,您可以使用它load
并dump
与存档进行交互。
解决方案 6:
如果您需要序列化,但不需要其他程序中的数据,我强烈推荐该shelve
模块。将其视为持久字典。
myData = shelve.open('/path/to/file')
# Check for values.
keyVar in myData
# Set values
myData[anotherKey] = someValue
# Save the data for future use.
myData.close()
解决方案 7:
为了完整起见,我们应该包括 ConfigParser 和 configparser,它们分别是 Python 2 和 Python 3 标准库的一部分。此模块读取和写入 config/ini 文件,并且(至少在 Python 3 中)在很多方面表现得像字典。它还有一个额外的好处,那就是您可以将多个字典存储到 config/ini 文件的不同部分并调用它们。太棒了!
Python 2.7.x 示例。
import ConfigParser
config = ConfigParser.ConfigParser()
dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}
# Make each dictionary a separate section in the configuration
config.add_section('dict1')
for key in dict1.keys():
config.set('dict1', key, dict1[key])
config.add_section('dict2')
for key in dict2.keys():
config.set('dict2', key, dict2[key])
config.add_section('dict3')
for key in dict3.keys():
config.set('dict3', key, dict3[key])
# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()
# Read the configuration from a file
config2 = ConfigParser.ConfigParser()
config2.read('config.ini')
dictA = {}
for item in config2.items('dict1'):
dictA[item[0]] = item[1]
dictB = {}
for item in config2.items('dict2'):
dictB[item[0]] = item[1]
dictC = {}
for item in config2.items('dict3'):
dictC[item[0]] = item[1]
print(dictA)
print(dictB)
print(dictC)
Python 3.X 示例。
import configparser
config = configparser.ConfigParser()
dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'}
dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'}
dict3 = {'x':1, 'y':2, 'z':3}
# Make each dictionary a separate section in the configuration
config['dict1'] = dict1
config['dict2'] = dict2
config['dict3'] = dict3
# Save the configuration to a file
f = open('config.ini', 'w')
config.write(f)
f.close()
# Read the configuration from a file
config2 = configparser.ConfigParser()
config2.read('config.ini')
# ConfigParser objects are a lot like dictionaries, but if you really
# want a dictionary you can ask it to convert a section to a dictionary
dictA = dict(config2['dict1'] )
dictB = dict(config2['dict2'] )
dictC = dict(config2['dict3'])
print(dictA)
print(dictB)
print(dictC)
控制台输出
{'key2': 'keyinfo2', 'key1': 'keyinfo'}
{'k1': 'hot', 'k2': 'cross', 'k3': 'buns'}
{'z': '3', 'y': '2', 'x': '1'}
config.ini 的内容
[dict1]
key2 = keyinfo2
key1 = keyinfo
[dict2]
k1 = hot
k2 = cross
k3 = buns
[dict3]
z = 3
y = 2
x = 1
解决方案 8:
如果保存到 JSON 文件,最好和最简单的方法是:
import json
with open("file.json", "wb") as f:
f.write(json.dumps(dict).encode("utf-8"))
解决方案 9:
我的用例是将多个 JSON 对象保存到一个文件中,marty 的答案对我有些帮助。但对于我的用例来说,答案并不完整,因为每次保存新条目时它都会覆盖旧数据。
要将多个条目保存在文件中,必须检查旧内容(即先读后写)。保存 JSON 数据的典型文件将具有list
或object
作为根。因此,我认为我的 JSON 文件始终具有list of objects
,并且每次向其中添加数据时,我只需先加载列表,将新数据附加到其中,然后将其转储回文件的只写实例(w
):
def saveJson(url,sc): # This function writes the two values to the file
newdata = {'url':url,'sc':sc}
json_path = "db/file.json"
old_list= []
with open(json_path) as myfile: # Read the contents first
old_list = json.load(myfile)
old_list.append(newdata)
with open(json_path,"w") as myfile: # Overwrite the whole content
json.dump(old_list, myfile, sort_keys=True, indent=4)
return "success"
新的 JSON 文件将如下所示:
[
{
"sc": "a11",
"url": "www.google.com"
},
{
"sc": "a12",
"url": "www.google.com"
},
{
"sc": "a13",
"url": "www.google.com"
}
]
注意:要使此方法起作用,必须有一个名为的文件file.json
作为初始数据[]
PS:与原始问题无关,但这种方法也可以进一步改进,首先检查我们的条目是否已经存在(基于一个或多个键),然后再附加并保存数据。