python - 我需要一个类来创建位于磁盘上的字典文件

标签 python

我想创建一个非常非常大的字典,并且我想将它存储在磁盘上,以免占用我的内存。基本上,我的需求是 cPickle 和 dict 类之间的交叉,因为它是 Python 视为字典的类,但恰好存在于磁盘上。

我的第一个想法是围绕一个简单的 MySQL 表创建某种包装器,但我必须将类型存储在 MySQL 甚至不希望支持开箱即用的结构条目中。

最佳答案

最简单的方法是 shelve模块,其工作方式几乎与字典完全相同:

import shelve
myshelf = shelve.open("filename") # Might turn into filename.db
myshelf["A"] = "First letter of alphabet"
print myshelf["A"]
# ...
myshelf.close()   # You should do this explicitly when you're finished

请注意 module documentation 中的注意事项关于更改存储在架子上的可变值(列表、字典等)(可以,但需要更多的摆弄)。它在底层使用 (c)pickle 和 dbm,因此它会愉快地存储您可以 pickle 的任何内容。

我不知道它相对于其他解决方案的性能如何,但它不需要任何自定义代码或第三方库。

关于python - 我需要一个类来创建位于磁盘上的字典文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4233923/

相关文章:

Python 请求无效 header 值

python - 只导入一个类的静态方法

python - 如何将 Python 连接到 MySQL 数据库...?

python - 类型错误 : __init__() got an unexpected keyword argument 'n_components'

python - Py_buffer在2.x中的用途 "multi-dimensional array"是什么?

python - lxml:在给定位置插入标签

python - x = myList[ :] vs myList[:] = x 中冒号运算符的行为

python - Pandas:检查重复行中至少有一个值是否为 1

python 算法: how to efficiently find if two integer sets are intersected?

python - 如何对表示元组的字符串列表进行排序?