1

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]
Chaban33
  • 1,362
  • 11
  • 38
  • Does this answer your question? [How can I make a python dataclass hashable without making them immutable?](https://stackoverflow.com/questions/52390576/how-can-i-make-a-python-dataclass-hashable-without-making-them-immutable) – 9769953 Jul 21 '22 at 11:33
  • Note that the suggested duplicate also has answers with a solution to do this for immutable dataclasses, which might also work for your case. – 9769953 Jul 21 '22 at 11:34
  • when access items in a dict you have to use the same key as you constructed it with. `FirstClass` (the class itself) is not the same as `FirstClass(name="default_name")` (an instance of that class) – Anentropic Jul 21 '22 at 11:36
  • @9769953 I got perfect answer for my needs from Pranav Hosangadi, thank you – Chaban33 Jul 21 '22 at 11:37

1 Answers1

3

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
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70