[Python] how to convert a dict to a dataclass (reverse of asdict)?

Discussão em 'Python' iniciado por Stack, Agosto 31, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página