要更新/修改sh中key的值吗

2024-09-28 05:40:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据(即{'/domflight': 10, '/intlflight': 20}),想将'/domflight'的值修改为50。下面是我的代码,我正在尝试做,但没有运气。在

import shelve
s = shelve.open('/tmp/test_shelf.db')
try:
        print s['key1']
        s['key1']['/domflight'] = 50
finally:
        s.close()

s = shelve.open('/tmp/test_shelf.db', writeback=True)
try:
        print s['key1']
finally:
        s.close()

Tags: 数据代码testclosedbopentmpshelve
1条回答
网友
1楼 · 发布于 2024-09-28 05:40:47

搁置无法检测对嵌套可变对象的更改。在嵌套字典中设置键不会触发保存。在

请重新设置词典:

nested_dict = s['key1']
nested_dict['/domflight'] = 50
s['key1'] = nested_dict

是对s['key1']的赋值触发了保存。在

从技术上讲,sUserDict.DictMixin类的一个子类,具有自定义的__setitem__方法。直接分配给s对象中的键将调用该方法并保存更改。但是分配给一个嵌套在键下的可变对象不会触发对__setitem__的调用,因此不会检测到更改,也不会保存任何内容。在

这是covered in the documentation

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).

相关问题 更多 >

    热门问题