首页 > 解决方案 > 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对象就像字典一样工作。所以我之前保存的方式应该可以工作,但不能。

标签: pythonpython-3.xdictionaryshelve

解决方案


推荐阅读