嵌套字典中的setdefault()?

setdefault() in nested dictionary?

尝试使用 setdefult() 将值存储在搁置文件中的嵌套字典中。有什么简单的方法可以做到这一点?下面的代码似乎使值不可变,例如,最后一行无法将 'price' 值更改为 25。

room_data = shelve.open("data")

room_data.setdefault("key", {"type": "Standard Single", "available": 5, "price": 50, "adults": 1, "children": 0})

room_data["key"]["price"] = 25

我希望它能与 shelve 一起运行,然后再添加 SQL,但现在学习它可能更容易。让我知道你的想法。谢谢。

你必须设置writeback=True:

room_data = shelve.open("data", writeback=True)

然后在改变一个值后调用room_data.sync()

room_data.setdefault("key", {"type": "Standard Single", "available": 5, "price": 50, "adults": 1, "children": 0})

room_data["key"]["price"] = 25

room_data.sync()

否则设置了值但不能改变设置值。

来自 shelve.open 上的注释:

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