让我们说我有一个大的,100兆字节的字典,我想把它放到磁盘上。我正在使用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.
答案 0 :(得分:6)
在这里你搁置了一个简单的字典,并通过密钥myDict
:
import shelve
myDict = {"a" : 1, "b" : 2}
myShelvedDict = shelve.open("my_shelved_dictionary.db")
myShelvedDict["myDict"] = myDict
请注意,字典的内容必须是可选择的,就像要搁置的任何内容一样。
如果你想在shelve中复制字典的结构,即没有myDict
键但是字典的键直接作为书架的键,你可以使用update
方法搁置:
myShelvedDict.update(myDict)
shelve
界面与dict
界面有很大重叠。