简体   繁体   中英

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

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.

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]) 

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM