the dataclasses module lets users make a dict from a dataclass reall conveniently, like this:
from dataclasses import dataclass, asdict
@dataclass
class MyDataClass:
''' description of the dataclass '''
a: int
b: int
# create instance
c = MyDataClass(100, 200)
print(c)
# turn into a dict
d = asdict(c)
print(d)
But i am trying to do the reverse process: dict -> dataclass.
The best that i can do is unpack a dict back into the predefined dataclass.
# is there a way to convert this dict to a dataclass ?
my_dict = {'a': 100, 'b': 200}
e = MyDataClass(**my_dict)
print(e)
How can i achieve this without having to pre-define the dataclass (if it is possible) ?
You can use make_dataclass
:
from dataclasses import make_dataclass
my_dict = {"a": 100, "b": 200}
make_dataclass(
"MyDynamicallyCreatedDataclass", ((k, type(v)) for k, v in my_dict.items())
)(**my_dict)