I need to save a dataclasses object by one of its attributes user_id
, and frequently query the user_id
and delete it if the key exists. The UserInfo
class is defined below:
@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]
So far I can only think of using the built-in dict()
(Or the Dict from typing in Python3) to store it: user_id
as key, and UserInfo
object as value. So deletion uses del keyword(Or pop? not sure which is better/Pythonic). But I was wondering if there's a more efficient solution?
CodePudding user response:
When you need to have a collection and query it by a key there isn't really a way to go about it that will be better than using a dict
Regarding del vs pop, since you say that the key will not always exist I would go with pop, but you can always use del and wrap it in try/except