Issue
How can I make this work, I need to get values from dictionary by class as a key.
But I get TypeError: unhashable type: 'FirstClass'
from dataclasses import dataclass
@dataclass
class FirstClass():
name: str
@dataclass
class SecondClass():
name: str
MAPPER = {FirstClass: 888, SecondClass: 999}
itr_list = [FirstClass(name="default_name"), SecondClass(name="default_name")]
for itr in itr_list:
get_key = MAPPER[itr]
Solution
Your problem is that you use the type FirstClass
and SecondClass
to define MAPPER
, but you use an instance of those classes to lookup MAPPER[itr]
. It will work if you use the type instead, like so: MAPPER[type(itr)]
.
for itr in itr_list:
get_key = MAPPER[type(itr)]
print(get_key)
will output
888
999
Answered By - Pranav Hosangadi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.