[英]How to load 2 big dict in Python?
我是Python的新手。 從兩個文件加載兩個字典時,出現內存錯誤。 這兩個文件是
with open(filename, 'rb') as f:
hashtable_album = {}
for line in f:
# print i
p = 0
q = line.find("####")
# print p
# print q
itembuf = line[p:q]
# print itembuf
dictbuf = line[q + 4:-1]
# print line
a = json.loads(dictbuf)
# print a
# print type(a)
hashtable_album[itembuf] = a
f.close()
with open(filename2, 'rb') as f2:
hashtable_item={}
i=0
for line in f:
print len(dic)
print i
#print line
p = 0
q = line.find("####")
# print p
# print q
itembuf = line[p:q]
# print itembuf
dictbuf = line[q + 4:-1]
# print line
a = json.loads(dictbuf)
#print a
# print type(a)
hashtable_item[itembuf] = a
i=i+1
f2.close()
第一個文件大約為400MB,大於第二個文件的大約200MB,我可以成功加載第一個文件,但是當我加載第二個文件時,出現內存錯誤
Traceback (most recent call last):
File "E:/py_workspace/1.0_memory_error.py", line 44, in <module>
hashtable_item[itembuf] = a
MemoryError
如果我先更改了將文件加載為讀取文件2的順序,然后又更改了文件1,則在加載第二個文件時也會出現內存錯誤。 我想內存錯誤來自dict,所以我將file1加載為后清除了dict
hashtable_album = {}
然后繼續加載file2。 這次它沒有內存錯誤。 但是我需要同時使用這兩個字典。 那么如何將它們一起加載?
提示:我嘗試了cPickle來保存字典,但無法正常工作,並且我也遇到了內存錯誤。
您可能正在運行32位python。
通過驗證
$ python -c "import sys; print sys.maxint" // 64-bit python
9223372036854775807
$ python-32 -c "import sys; print sys.maxint" // 32-bit
2147483647
如果無法擺脫在32位空間中運行的問題,那么您有兩種選擇
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.