如何用现有字典填充货架

7 投票
1 回答
4204 浏览
提问于 2025-04-16 21:12

假设我有一个很大的字典,大小有几百兆,我想把它放到硬盘上做成一个存储架。我正在使用pypar和MPI来生成一个干净的主列表。有什么好的方法可以实现这个目标呢?举个例子:

# much earlier
masterDict = shelve.open( 'aShelveFile' )
# .. . . . . 
# then we work out which parts of masterDict to keep
# and we put into aCleanDict
# then use mpi pypar to send the cleaned bits to the master rank
if pypar.rank() == 0:
  tempdict = {}
  for p in range(1,pypar.size()):
    tempdict.append(pypar.receive(p))
  for l1 in tempdict:
    for l2 in l1:
      realDict.append(l2)
  for p in range(1,pypar.size()):
    pypar.send(realDict,p)

  # now realDict has all the cleaned bits
  # which we send to the other hosts
else:
  pypar.send(aCleanDict, 0 )
  aCleanDict = pypar.receive( 0 )

# now to replace masterDict  with aCleanDict
# note: cannot send shelve dictonaries using pypar

# insert stackover flow code here.

1 个回答

7

在这里,你可以把一个简单的字典存储起来,并通过一个叫 myDict 的键来访问它:

import shelve
myDict = {"a" : 1, "b" : 2}
myShelvedDict = shelve.open("my_shelved_dictionary.db")
myShelvedDict["myDict"] = myDict

需要注意的是,字典里的内容必须是可以被“腌制”的,也就是可以被存储的,像其他任何要存储的东西一样。

如果你想在存储中复制字典的结构,也就是说,不想用 myDict 这个键,而是直接用字典里的键作为存储的键,你可以使用 update 方法来实现:

myShelvedDict.update(myDict)

shelve 接口和 dict 接口有很多相似之处。

撰写回答