Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get values from dictionary by class as a key

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading