简体   繁体   English

不使用pickle将运行时字典保存为python代码

[英]Save dictionary on runtime as python code not using pickle

I've a dictionary loaded in a variable as follows 我将字典加载到变量中,如下所示

>>constellation_dict["AND"]
array([[  2.35357132e+01,   3.51897736e+01],
       [  2.34684925e+01,   3.51880264e+01],
       [  2.34012642e+01,   3.51860695e+01],
       [  2.33340359e+01,   3.51838989e+01],
       [  2.32668228e+01,   3.51815186e+01],
       ....
       [  2.36029453e+01,   3.51913109e+01]])

Dictionary has arround 88 keys and each value consts of an arrays of tenths of pairs. 字典具有大约88个键,十分之一对数组的每个值const。 All data is invariable (correspond to constellations border) 所有数据都是不变的(对应于星座边界)

Currently I can load (and eventualy save it) with pickle methods. 目前,我可以使用pickle方法加载(并最终保存它)。 My question is: Is there any way to store it as python code or similar so I can load it as module part and not having to read a file every time I call the module? 我的问题是:有什么方法可以将其存储为python代码或类似代码,以便我可以将其作为模块部分加载,而不必在每次调用模块时都读取文件?

I tried to use json module to turn it into simple code but it says that "object is not serializable". 我试图使用json模块将其转换为简单的代码,但它表示“对象不可序列化”。

By the way, these are the methods I'm using currently to load/save dictionary 顺便说一下,这些是我目前正在使用的加载/保存字典的方法

import pickle
def save_obj(obj, name, protocol = pickle.HIGHEST_PROTOCOL):
    with open('obj/'+ name + '.pkl', 'wb') as f:
        #posible alternative protocol 0 (text_format)
        pickle.dump(obj, f, protocol)

def load_obj(name ):
    with open('obj/' + name + '.pkl', 'r') as f:
        return pickle.load(f)

constellation_dictionary = load_obj('const_dict.dat')

Have you tried fromfile and tofile ( http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html ). 您是否尝试过fromfile和tofile( http://docs.scipy.org/doc/numpy/reference/genic/numpy.fromfile.html )。 It's easy and fast. 简单,快速。

Other option is create a module with the dictionary inside as a variable, like: data.py: 另一个选择是使用字典作为变量创建一个模块,例如:data.py:

consmap = {'AND' : [[....]],
            ...
           'OTHERKEY' : [[]]}

and in other module: 在其他模块中:

from data import consmap
print consmap['AND']

If you want an alternative to pickle or json , you can use klepto . 如果要代替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}

With klepto , if you had used serialized=True , the dictionary would have been written to memo.pkl as a pickled dictionary instead of with clear text (as importable python code). 使用klepto ,如果您使用serialized=True ,则该字典将作为腌制的字典而不是使用明文(作为可导入的python代码)写到memo.pkl中。

You can get klepto here: https://github.com/uqfoundation/klepto 您可以在此处获取kleptohttps//github.com/uqfoundation/klepto

You can configure klepto to store dictionaries to a file, to a directory context, or to a SQL database. 您可以配置klepto将字典存储到文件,目录上下文或SQL数据库中。 The API is the same for whatever you choose as the backend archive. 无论选择什么作为后端存档,API都是相同的。 It gives you an "archivable" dictionary with which you can use load and dump to interact with the archive. 它为您提供了一个“可存档”词典,您可以使用该词典使用loaddump与存档进行交互。 You can also choose the storage format, where klepto can be configured to store your data with pickle or with json or as a string, or as a hash, or several other methods for encoding the key and value in the persistent store. 您还可以选择存储格式,其中klepto可以配置为使用picklejson或作为字符串,作为散列或其他在持久存储中编码键和值的其他方法来存储数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM