存储Python词典

时间:2011-08-17 22:06:48

标签: python json dictionary save pickle

我习惯使用.csv文件将数据输入和输出Python,但是存在明显的挑战。关于在json或pck文件中存储字典(或字典集)的简单方法的任何建议?例如:

data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"

我想知道如何保存它,以及如何将其加载回来。

9 个答案:

答案 0 :(得分:346)

Pickle保存:

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)

有关protocol参数的其他信息,请参阅the pickle module documentation

Pickle加载

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_keysindent,以获得漂亮的结果。参数 sort_keys 将按字母顺序对键进行排序,缩进将使用indent=N空格缩进数据结构。

json.dump(data, fp, sort_keys=True, indent=4)

JSON加载

with open('data.json', 'r') as fp:
    data = json.load(fp)

答案 1 :(得分:31)

最小的例子,直接写入文件:

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)

答案 2 :(得分:7)

另请参阅加速包ujson。 https://pypi.python.org/pypi/ujson

import ujson
with open('data.json', 'wb') as fp:
    ujson.dump(data, fp)

答案 3 :(得分:5)

要写入文件:

import json
myfile.write(json.dumps(mydict))

从文件中读取:

import json
mydict = json.loads(myfile.read())

myfile是您存储dict的文件的文件对象。

答案 4 :(得分:5)

如果您在序列化之后但不需要其他程序中的数据,我强烈推荐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()

答案 5 :(得分:3)

如果您想要替代picklejson,可以使用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可能是对pickle本身进行挑选的更好选择,因为dill几乎可以在python中序列化任何内容。 klepto也可以使用dill

您可以在此处dill获取https://github.com/uqfoundation/dill

前几行中的额外mumbo-jumbo是因为klepto可以配置为将字典存储到文件,目录上下文或SQL数据库。无论您选择哪种API作为后端存档,API都是相同的。它为您提供了一个“可存档”字典,您可以使用loaddump与存档进行交互。

答案 6 :(得分:2)

这是一个古老的主题,但为了完整起见,我们应该包括ConfigParser和configparser,它们分别是Python 2和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 config
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 config to file
f = open('config.ini', 'w')
config.write(f)
f.close()

# read config from 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 config
config['dict1'] = dict1
config['dict2'] = dict2
config['dict3'] = dict3

# save config to file
f = open('config.ini', 'w')
config.write(f)
f.close()

# read config from 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

答案 7 :(得分:0)

如果保存到json文件,最好和最简单的方法是:

import json
with open("file.json", "wb") as f:
    f.write(json.dumps(dict).encode("utf-8"))

答案 8 :(得分:0)

我的用例是将多个JSON对象保存到一个文件中,marty's answer有所帮助。但是,为我的用例服务,答案并不完整,因为每次保存新条目时,它都会覆盖旧数据。

要将多个条目保存在一个文件中,必须检查旧内容(即在写入之前先读取)。包含JSON数据的典型文件将以listobject作为根。因此,我认为我的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:与原始问题无关,但是通过首先检查我们的条目是否已经存在(基于一个或多个键),然后仅附加并保存数据,也可以进一步改进此方法。

相关问题