【问题标题】:Most efficient data structure for add and remove by key in Python3Python3中按键添加和删除的最有效数据结构
【发布时间】: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


    【解决方案1】:

    当你需要一个集合并通过一个键查询它时,没有比使用字典更好的方法了

    关于 del 与 pop,既然你说密钥并不总是存在,我会选择 pop,但你总是可以使用 del 并将其包装在 try/except 中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      相关资源
      最近更新 更多