Home > database >  How to access dataclass variable when the dataclass is in a dictionary?
How to access dataclass variable when the dataclass is in a dictionary?

Time:01-04

I have a dictionary and it has dataclasses in it. When I loop the dictionary, I want to print out a variable of the dataclass through the dictionary. Lemme give an example.

from dataclasses import dataclass

my_dict = {}

@dataclass
class my_class:
    name: str
    zom: int

my_dict["Hello"] = my_class("Zarg", 1)
my_dict["Hi"] = my_class("Zoog", 2)

for index in my_dict:
    print(my_dict[index]) #This is where I want to get the variable "zom" from the dataclass. I tried doing my_dict[index].zom but it didn't work.

CodePudding user response:

Try:

for key, value in my_dict.items():
     print(value.zom)

Or if you won't need the dictionary keys:

for value in my_dict.values():
    print(value.zom)

This will print:

1
2

CodePudding user response:

Your example works fine for me in Python version 3xx

from dataclasses import dataclass

my_dict = {}

@dataclass
class my_class:
    name: str
    zom: int

my_dict["Hello"] = my_class("Zarg", 1)
my_dict["Hi"] = my_class("Zoog", 2)

# option 1 works in Python 3xx
for index in my_dict:
    print(my_dict[index].zom) 

# option 2 works in Python 3xx too
for key, value in my_dict.items():
    print(value.zom)
  •  Tags:  
  • Related