gpt4 book ai didi

python - 搁置,Python,更新字典

转载 作者:太空宇宙 更新时间:2023-11-04 07:02:43 26 4
gpt4 key购买 nike

我在 Python 中使用 Shelve 时遇到问题:

In [391]: x
Out[391]: {'broken': {'position': 25, 'page': 1, 'letter': 'a'}}

In [392]: x['broken'].update({'page':1,'position':25,'letter':'b'})

In [393]: x
Out[393]: {'broken': {'position': 25, 'page': 1, 'letter': 'a'}}

不明白为什么不更新?有什么想法吗?

最佳答案

这包含在 documentation 中.基本上,关键字参数 writebackshelve.open 负责:

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

来自同一页面的示例:

d = shelve.open(filename) # open -- file may get suffix added by low-level
# library
# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4) # this works as expected, but...
d['xx'].append(5) # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx'] # extracts the copy
temp.append(5) # mutates the copy
d['xx'] = temp # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close() # close it

关于python - 搁置,Python,更新字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13996907/

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