将元组和int密钥字典写入文件

时间:2016-12-13 15:24:26

标签: python json dictionary tuples pickle

我正在尝试将一个字典写入(并从中读取)一个文件,其中键是元组和int的组合,如下所示:

Q = {((True, False, 1, 0), 1): 100}

我已经尝试了pickle,json和csv,但似乎无法解决复杂的关键问题,而且我似乎无法在这种类型的字典上找到太多文档。

#json code which works for a tuple only as the key 

def write_file(mat):
    with open('file.json', 'w') as f:
         json.dump(mat, f)

def read_file():
    with open('file.json', 'r') as f:
        try:
            data = json.load(f)
        except ValueError:
            data = {}
    return data

3 个答案:

答案 0 :(得分:0)

Pickle对我来说很好:

Q = {((True, False, 1, 0), 1): 100}

import pickle

with open("test", "wb") as file:
    pickle.dump(Q, file)
with open("test", "rb") as file:
    QQ=pickle.load(file)
print(QQ)

将输出:

  

{((True,False,1,0),1):100}

这是在python 2.7

您是否可以发布您的pickle代码进行比较,包括错误消息?

答案 1 :(得分:0)

这可能会解决您的问题。我基本上将你拥有的元组转换为字符串,创建一个新的字典。我将其存储到json文件中,然后使用eval内置函数来获取元组。虽然这样做有效,但如果您不知道数据的来源,请小心使用eval函数。

Q = {((True, False, 1, 0), 1): 100}
Q_new = dict([(str(i),j) for i,j in Q.items()])

def write_file(mat):
    with open('file.json', 'w') as f:
        json.dump(mat, f)

def read_file():
    with open('file.json', 'r') as f:
        data = json.load(f)
        return dict([(eval(str(i)),j) for i,j in Q.items()])

write_file(Q_new)
print(read_file())

输出:

{((True, False, 1, 0), 1): 100}

答案 2 :(得分:0)

正如我所说,pickle可以轻松地将复杂的密钥保存并恢复到字典的内容(并将其读回)。

如果 真的 想要使用JSON格式来执行此操作,您可以利用这一事实,并将pickle d数据存储为值"普通"中的特殊键Python dict

import json
import pickle

def my_dump(obj, *args, **kwargs):
    if isinstance(obj, dict):
        pkl = {'_python_object': pickle.dumps(obj)}
        return _orig_dump(pkl, *args, **kwargs)
    return _orig_dump(obj, *args, **kwargs)

# monkey-patch json module to use our dump function (optional)
_orig_dump = json.dump
json.dump = my_dump

def as_python_object(dct):
    if '_python_object' in dct:
        return pickle.loads(str(dct['_python_object']))
    return dct

def write_file(mat):
    with open('file.json', 'w') as f:
         json.dump(mat, f)

def read_file():
    with open('file.json', 'r') as f:
        data = json.load(f, object_hook=as_python_object)
    return data

Q = {((True, False, 1, 0), 1): 100}
write_file(Q)
d = read_file()
print(d)  # -> {((True, False, 1, 0), 1): 100}