[Python] Python dataclass from a nested dict

Discussão em 'Python' iniciado por Stack, Julho 15, 2025.

  1. Stack

    Stack Membro Participativo

    The standard library in 3.7 can recursively convert a dataclass into a dict (example from the docs):

    from dataclasses import dataclass, asdict
    from typing import List

    @dataclass
    class Point:
    x: int
    y: int

    @dataclass
    class C:
    mylist: List[Point]

    p = Point(10, 20)
    assert asdict(p) == {'x': 10, 'y': 20}

    c = C([Point(0, 0), Point(10, 4)])
    tmp = {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
    assert asdict(c) == tmp


    I am looking for a way to turn a dict back into a dataclass when there is nesting. Something like C(**tmp) only works if the fields of the data class are simple types and not themselves dataclasses. I am familiar with jsonpickle, which however comes with a prominent security warning.


    EDIT:

    Answers have suggested the following libraries:

    • dacite
    • mashumaro (I used for a while, works well but I quickly ran into tricky corner cases)
    • pydantic (works very well, excellent documentation and fewer corner cases)

    Continue reading...

Compartilhe esta Página