将内存中的变量保存到文件中

Saving a variable as it is in the memory to a file

根据

,我有一个 2280 字节的字典
sys.getsizeof(myDictionary)

当我用 pickle 将它保存到文件时

with open("dictionary.txt", "wb") as fp:   #Pickling
    pickle.dump(myDictionary, fp)

突然变大了100KB左右

我能否获得该词典的精确二进制表示并将其保存到文件中? 然后再次将此文件作为字典访问?

或者如果不可能,也许可以使用另一种编程语言?使该文件尽可能小很重要

引自 docs 关于 sys.getsizeof:

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

好吧,Python 中的对象引用其他对象 很多 ,所以很可能,getsizeof 在这里帮不上什么忙。

例如:

>>> a = {'a': 1, 'b': 2}
>>> sys.getsizeof(a)
240 # WUT
len(pickle.dumps(a))
28 # looks legit

然后做:

>>> p = [1,2,3,4,5]
>>> a['k'] = p
>>> sys.getsizeof(a)
240 # WUT
>>> len(pickle.dumps(a))
51 # looks legit

所以,这个对象消耗的内存量显然取决于表示。如果你只想保存字典,那么,你只需要保存一堆指向基本上无处可去的指针(因为当你加载保存的数据时,它们将无效)。您可以使用 this recursive recipe 查找对象的大小及其内容。

如果您希望文件尽可能小,请考虑压缩字典中的值或使用不同的数据表示形式。