我习惯使用CSV文件在Python中输入和输出数据,但这存在明显的挑战。是否有简单的方法将字典(或字典集)存储在JSON或pickle文件中?

例如:

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

我想知道如何保存这个,然后如何加载它回来。


当前回答

最小示例,直接写入文件:

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)

其他回答

较短的代码

保存和加载所有类型的python变量(包括字典),每个变量只需一行代码。

data = {'key1': 'keyinfo', 'key2': 'keyinfo2'}

保存:

pickle.dump(data, open('path/to/file/data.pickle', 'wb'))
   

加载:

data_loaded = pickle.load(open('path/to/file/data.pickle', 'rb'))

也许这很明显,但在我试图使它更短之前,我在顶部的答案中使用了两行解。

如果你想要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是一个pickle的字典,而不是清晰的文本。

你可以在这里获得klepto: https://github.com/uqfoundation/klepto

对于pickle来说,Dill可能是比pickle本身更好的选择,因为Dill可以序列化python中的几乎任何东西。小偷也可以用莳萝。

你可以在这里买到莳萝:https://github.com/uqfoundation/dill

前几行中出现的额外冗赘是因为可以将klepto配置为将字典存储到文件、目录上下文或SQL数据库。无论您选择什么作为后端存档,API都是相同的。它为您提供了一个“可存档的”字典,您可以使用它来加载和转储与存档进行交互。

我的用例是将多个JSON对象保存到一个文件中,marty的回答在一定程度上帮助了我。但是为了服务于我的用例,答案并不完整,因为每次保存新条目时它都会覆盖旧数据。

要在一个文件中保存多个条目,必须检查旧内容(即先读后写)。持有JSON数据的典型文件将以列表或对象作为根。所以我认为我的JSON文件总是有一个对象列表,每次我向它添加数据时,我只是先加载列表,在其中追加我的新数据,并将其转储回file (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:与原始问题无关,但这种方法也可以进一步改进,首先检查我们的条目是否已经存在(基于一个或多个键),然后再追加并保存数据。

最小示例,直接写入文件:

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)

写入文件:

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

从文件中读取:

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

Myfile是存放dict的文件的file对象。