【发布时间】:2021-10-31 12:42:51
【问题描述】:
我需要通过属性user_id 保存一个dataclasses 对象,并经常查询user_id 并在键存在时将其删除。 UserInfo 类定义如下:
@dataclass(frozen=True)
class UserInfo:
user_id: int
book: str
bookshelf_color: str
money: int
size: int
# operation for this data structure D
if user_id in D:
del D[user_id]
到目前为止,我只能想到使用内置的dict()(或Python3中输入的Dict)来存储它:user_id作为键,UserInfo作为值。所以删除使用 del 关键字(或 pop?不确定哪个更好/Pythonic)。但我想知道是否有更有效的解决方案?
【问题讨论】:
标签: python python-3.x dictionary system python-dataclasses