python - Python搁置不保存嵌套键
问题描述
我正在使用该shelve
模块来保存一些 Python 对象(示例中的字符串)。
当我尝试将对象保存为嵌套键时,它不会被保存。
class Car:
def __init__(self, ID):
self.id = ID
def save_to_shelf(self):
with shelve.open('shelf') as shelf:
if not shelf.get('users'):
shelf['users'] = {}
print(shelf['users'])
try:
shelf['users'][self.id] = "hello"
except Exception as e:
print(e)
print('saved')
print(shelf['users'])
car = Car(123)
car.save_to_shelf()
代码应打印:
{}
saved
{123: hello}
但相反,它打印:
{}
saved
{}
意味着它没有被保存
如果我打印键的值,它会给出KeyError
shelf['users'][self.id] = "hello"
print(shelf['users'][self.id])
错误
Traceback (most recent call last):
File "P:/Python practice/Shelll/main.py", line 3, in <module>
car.save_to_shelf()
File "P:/Python practice/Shelll\db.py", line 20, in save_to_shelf
print(shelf['users'][self.id])
KeyError: '123'
如果我在保存时执行以下操作,我可以保存它而 不是
with shelve.open('shelf') as shelf:
shelf['users'][self.id] = "hello"
这有效
with shelve.open('shelf') as shelf:
USERS = shelf['users']
USERS[self.id] = self.id
shelf['users'] = USERS
# or this works
# with shelve.open('shelf') as shelf:
# shelf['users'] = {self.id:"hello"}
我想了解这背后的原因。据我所知,shelve
对象就像字典一样工作。所以我之前保存的方式应该可以工作,但不能。
解决方案
推荐阅读
- javascript - 协助解决 Javascript 问题(培训中的学生)
- python - 数据框从旧行和旧列转换为具有新列的一行
- sql - if else sql中的情况
- python - ValueError:模型的特征数量必须与输入匹配。模型 n_features 为 11,输入 n_features 为 2
- html - js打印只能在手机模式下打开,如何在pc模式下打印?
- c++ - c++ 错误:没有匹配的函数来调用我的图形代码的...
- r - print(list(1,2,3)) 又长又丑;如何使用 print 打印列表 [即,无需在 print 与 paste0 之间切换的漂亮打印]
- python - 如何解决pycharm中的“缺少键盘映射”问题?
- r - 是否使用 base 中的 comment() 将信息分配给 R 对象会减慢代码速度?
- xilinx - Xilinx 的 ALPR 提供程序