【问题标题】:How to load 2 big dict in Python?如何在 Python 中加载 2 个大字典?
【发布时间】:2017-05-04 01:52:09
【问题描述】:

我是 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,则在加载第二个文件时也会出现内存错误。 我猜内存错误来自字典,所以我在加载 file1 后清除了字典

hashtable_album = {}

然后继续加载file2。这次它没有内存错误。 但我需要同时使用这两个字典。那么如何将它们一起加载呢?

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

【问题讨论】:

  • 同一脚本中的数据容器和比较器,是个非常糟糕的主意!对您很重要的数据,您保存在某处,但why don't use any database system ? 直接IO 总是引发错误(出现硬件性能错误)。您是否在“虚拟操作系统”下运行此代码?

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


【解决方案1】:

您可能正在运行 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。

【讨论】:

  • 谢谢你的建议,我会试试这些。
  • 我删除了 32 位 python 并更改了 64 位 python,然后我重新加载了我的 python 文件。它没有内存错误!太感谢了 ! @Ajeet
  • 不客气。 :) 不要忘记接受@Wenson 的答案。这样其他人就会知道它有效。
猜你喜欢
  • 2015-08-25
  • 2011-04-26
  • 2022-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-13
  • 2022-08-21
相关资源
最近更新 更多