gpt4 book ai didi

python - 使用 __setitem__ 在嵌套字典中设置项目

转载 作者:太空宇宙 更新时间:2023-11-03 11:32:02 30 4
gpt4 key购买 nike

这是我所做的,尝试为类似 dict 的数据库创建一个包装器,以及其他功能:

    class database(object):
def __init__(self, name):
self.name = name
self.db = anydbm.open(name, 'c')

def __getitem__(self, key):
key = str(key)
try:
self.db = anydbm.open(self.name, 'w')
except Exception,e:
raise e
else:
return cPickle.loads(self.db[key])
finally:
self.db.close()

def __setitem__(self, key, value):
key = str(key)
value = cPickle.dumps(value)
try:
self.db = anydbm.open(self.name, 'w')
except Exception,e:
print e
else:
self.db[key] = value
finally:
self.db.close()

当我尝试在嵌套的字典中定义新键时,似乎 getitem 返回的是一个值而不是一个引用,因此定义在 setitem 之后并没有最终被修改。

>>> from database import database
>>> db = database('test')
>>> db['a'] = {'alpha':'aaa'}
>>> db['a']['alpha'] = 'bbb'
>>> print db
{'a': {'alpha': 'aaa'}} //The value is not modified

最佳答案

嗯,你必须明白你在做什么:

db['a'] = {'alpha':'aaa'}

相当于

db.__setitem__('a', {'alpha':'aaa'})

所以这会将字典转储到磁盘。但是当你这样做的时候

db['a']['alpha'] = 'bbb'

你首先从磁盘加载字典

tmp = db.__getitem__('a') # except tmp is pushed on the stack

然后改变这个字典:

tmp['alpha'] = 'bbb'

这显然对转储到磁盘的数据没有影响,因为您的对象不再涉及。

要完成这项工作,您不能返回一个简单的字典,而是需要另一个对象来跟踪更改并将它们写回磁盘。

顺便说一句,你写的是shelve .它有同样的问题:

Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. By default modified objects are written only when assigned to the shelf (see Example). If the optional writeback parameter is set to True, all entries accessed are also cached in memory, and written back on sync() and close(); this can make it handier to mutate mutable entries in the persistent dictionary, but, if many entries are accessed, it can consume vast amounts of memory for the cache, and it can make the close operation very slow since all accessed entries are written back (there is no way to determine which accessed entries are mutable, nor which ones were actually mutated).

关于python - 使用 __setitem__ 在嵌套字典中设置项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16676177/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com