Home > Software engineering >  Get values from dictionary by class as a key
Get values from dictionary by class as a key

Time:07-21

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]

CodePudding user response:

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
  • Related