如何在Python中加载2个大字典?

时间:2016-12-19 03:26:54

标签: python json file out-of-memory reader

我是Python的新手。当我从两个文件加载两个dicts时出现内存错误。这两个文件是

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。而这次它没有内存错误。 但我需要同时使用这2个dicts。那么如何将它们加载在一起呢?

提示:我尝试使用cPickle来保存字典,但它无法正常工作,我也得到了内存错误。

1 个答案:

答案 0 :(得分:0)

您可能正在运行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位空间中运行,那么您有两个选项

  1. 学习C,并使用C进行处理。从文件的输入大小来看,严格使用内存(mallocs / callocs)可能允许你将所有内容保存在mem中。
  2. 如果您使用的算法允许map-reduce,那么学习map-reduce可能会更快,并且在每个步骤中进行部分文件处理,然后在最后一步中合并结果。
  3. 不确定,但您可能想尝试一下Cython。