[Python] Validating nested dict with Pydantic `create_model`

Discussão em 'Python' iniciado por Stack, Setembro 13, 2025.

  1. Stack

    Stack Membro Participativo

    I am using create_model to validate a config file which runs into many nested dicts. In the below example I can validate everything except the last nest of sunrise and sunset.

    class System(BaseModel):

    data: Optional[create_model('Data', type=(str, ...), daytime=(dict, ...))] = None

    try:
    p = System.parse_obj({
    'data': {
    'type': 'solar',
    'daytime': {
    'sunrise': 5,
    'sunset': 10
    }
    }})

    print(p.dict())
    vals = p.dict()
    print(vals['data']['daytime'], type(vals['data']['daytime']['sunrise']))

    except ValidationError as e:
    print(e)


    How can I incorporate a nested dict in create_model and ensure sunrise and sunset are validated? Is there any other way to validate this?

    Thanks for your feedback.

    Continue reading...

Compartilhe esta Página