我需要保存数据类型对象的属性user_id之一,并经常查询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?不确定哪一个更好/毕多尼)。但我想知道是否有更有效的解决方案?
发布于 2021-10-31 14:39:48
当您需要拥有一个集合并按键查询它时,没有比使用dict更好的方法了。
关于del vs pop,因为您说键将不总是存在,所以我将与pop一起使用,但是您总是可以使用del并将其包装在try/以外。
https://stackoverflow.com/questions/69786976
复制相似问题