In Pydantic 2, you can use MyModel.model_validate(my_dict) to generate a model from a dictionary. According to the documentation –

this is very similar to the __init__ method of the model, except it takes a dict rather than keyword arguments.

If you're Pydantic 1, the method is parse_obj instead.

Answer from Alex King on Stack Overflow
🌐
Pydantic
docs.pydantic.dev › latest › concepts › models
Models - Pydantic Validation
When using attributes to validate models, model instances will be created from both top-level attributes and deeper-nested attributes as appropriate. ... from pydantic import BaseModel, ConfigDict class PetCls: def __init__(self, *, name: str) -> None: self.name = name class PersonCls: def __init__(self, *, name: str, pets: list[PetCls]) -> None: self.name = name self.pets = pets class Pet(BaseModel): model_config = ConfigDict(from_attributes=True) name: str class Person(BaseModel): model_config = ConfigDict(from_attributes=True) name: str pets: list[Pet] bones = PetCls(name='Bones') orion = PetCls(name='Orion') anna = PersonCls(name='Anna', pets=[bones, orion]) anna_model = Person.model_validate(anna) print(anna_model) #> name='Anna' pets=[Pet(name='Bones'), Pet(name='Orion')]
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › models
Models - Pydantic
Pydantic's generics also integrate properly with mypy, so you get all the type checking you would expect mypy to provide if you were to declare the type without using GenericModel. ... Internally, pydantic uses create_model to generate a (cached) concrete BaseModel at runtime, so there is ...
🌐
Instructor
python.useinstructor.com › concepts › models
Using Pydantic Models for Structured Outputs - Instructor
The create method uses this prompt to generate the response. Use Optional and default to make fields optional when sent to the language model. from pydantic import BaseModel, Field from typing import Optional import instructor class User(BaseModel): ...
🌐
Pydantic
docs.pydantic.dev › latest › api › base_model
BaseModel - Pydantic Validation
Validate the given object with string data against the Pydantic model. ... create_model( model_name: str, /, *, __config__: ConfigDict | None = None, __doc__: str | None = None, __base__: None = None, __module__: str = __name__, __validators__: ( dict[str, Callable[..., Any]] | None ) = None, __cls_kwargs__: dict[str, Any] | None = None, __qualname__: str | None = None, **field_definitions: Any | tuple[str, Any], ) -> type[BaseModel]
Top answer
1 of 1
3

It's not entirely clear what you are trying to achieve, so here's my best guess:

Pydantic's create_model() is meant to be used when

the shape of a model is not known until runtime.

From your code it's not clear whether or not this is really necessary.

Here's how I would approach this.

(The code below is using Python 3.9 and above type hints. If you're using an earlier version, you might have to replace list with typing.List and dict with typing.Dict.)

Using a "Static" Model

from pydantic import BaseModel, create_model
from typing import Optional

class Data(BaseModel):
    type: str
    daytime: dict[str, int] # <- explicit types in the dict, values will be coerced

class System(BaseModel):
    data: Optional[Data]

system = {
    "data": {
        "type": "solar",
        "daytime": {
            "sunrise": 1,
            "sunset": 10
        }
    }
}

p = System.parse_obj(system)
print(repr(p))
# System(data=Data(type='solar', daytime={'sunrise': 1, 'sunset': 10}))

This will accept integers in daytime but not other types, like strings.

That means, something like this:

system = {
    "data": {
        "type": "solar",
        "daytime": {
            "sunrise": "some string",
            "sunset": 10
        }
    }
}

p = System.parse_obj(system)

will fail with:

pydantic.error_wrappers.ValidationError: 1 validation error for System
data -> daytime -> sunrise
  value is not a valid integer (type=type_error.integer)

If you want more control over how "daytime" is being parsed, you could create an additional model for it, e.g.:

class Daytime(BaseModel):
    sunrise: int
    sunset: int

class Data(BaseModel):
    type: str
    daytime: Daytime

class System(BaseModel):
    data: Optional[Data]

This will work as above however, only the parameters sunrise and sunset will be parsed and everything else that might be inside "daytime" will be ignored (by default).

Using a "Dynamic" Model

If you really need to create the model dynamically, you can use a similar approach:

class System(BaseModel):
    data: Optional[
        create_model(
            "Data",
            type=(str, ...),
            daytime=(dict[str, int], ...), # <- explicit types in dict
        )
    ] = None

system = {
    "data": {
        "type": "solar",
        "daytime": {
            "sunrise": 1,
            "sunset": 10
        }
    }
}

p = System.parse_obj(system)
print(repr(p))

will work, while

system = {
    "data": {
        "type": "solar",
        "daytime": {
            "sunrise": "abc",
            "sunset": 10
        }
    }
}

p = System.parse_obj(system)

will fail with

pydantic.error_wrappers.ValidationError: 1 validation error for System
data -> daytime -> sunrise
  value is not a valid integer (type=type_error.integer)
🌐
Medium
medium.com › @marcnealer › a-practical-guide-to-using-pydantic-8aafa7feebf6
A Practical Guide to using Pydantic | by Marc Nealer | Medium
August 3, 2024 - from pydantic import BaseModel class DefaultsModel(BaseModel): first_name: str = "jane" middle_names: list = [] last_name : str = "doe" The seems kinda obvious. There is however a problem and that is with the definition of the list. If you code a model in this way, only one list object is created and its shared between all instances of this model.
🌐
GitHub
github.com › pydantic › pydantic › discussions › 7982
running create_model on output of model_json_schema · pydantic/pydantic · Discussion #7982
October 31, 2023 - pydantic version: 2.4.2 pydantic-core version: 2.10.1 pydantic-core build: profile=release pgo=false install path: /Users/Brian/anaconda3/envs/valis_test/lib/python3.10/site-packages/pydantic python version: 3.10.12 | packaged by conda-forge | (main, Jun 23 2023, 22:39:40) [Clang 15.0.7 ] platform: macOS-10.14.6-x86_64-i386-64bit related packages: pydantic-extra-types-2.1.0 typing_extensions-4.8.0 fastapi-0.104.0 pydantic-settings-2.0.3 email-validator-2.1.0.post1 · Beta Was this translation helpful? Give feedback. ... There was an error while loading. Please reload this page. Something went wrong. There was an error while loading. Please reload this page. ... Thanks for reporting this. So this isn't a bug - in general, we don't support creating models from json schema.
Author   pydantic
Find elsewhere
🌐
Pydantic
docs.pydantic.dev › latest › examples › dynamic_models
Dynamic models - Pydantic Validation
What's new — we've launched Pydantic Logfire to help you monitor and understand your Pydantic validations. Models can be created dynamically using the create_model() factory function.
🌐
GitHub
github.com › pydantic › pydantic › issues › 9573
Create a model dynamically with create_model() specifying a subset of fields in V2 · Issue #9573 · pydantic/pydantic
June 5, 2024 - Discussed in #9449 Originally posted by tteguayco May 17, 2024 We're able to create a new model dynamically using create_model() like this: from pydantic import create_model base_model = ... new_model = create_model('MyNewModel', base_mo...
Author   tteguayco
🌐
Blue Book
lyz-code.github.io › blue-book › coding › python › pydantic
Pydantic - The Blue Book
There are some occasions where the shape of a model is not known until runtime. For this pydantic provides the create_model method to allow models to be created on the fly.
🌐
DataCamp
datacamp.com › tutorial › pydantic
Pydantic: A Guide With Practical Examples | DataCamp
June 25, 2025 - Let’s break down what’s happening in this model definition: Creating a Pydantic model: Your User class inherits from BaseModel, which gives it all of Pydantic's validation and serialization capabilities.
🌐
Real Python
realpython.com › python-pydantic
Pydantic: Simplifying Data Validation in Python – Real Python
April 3, 2024 - Here, you create new_employee_dict, a dictionary with your employee fields, and pass it into .model_validate() to create an Employee instance. Under the hood, Pydantic validates each dictionary entry to ensure it conforms with the data you’re expecting. If any of the data is invalid, Pydantic will throw an error in the same way you saw previously.
🌐
Orchestra
getorchestra.io › guides › pydantic-dynamic-model-creation-in-fastapi
Pydantic Dynamic Model Creation in FastAPI | Orchestra
March 28, 2024 - First, let's see a simple example where we create a model dynamically based on a given dictionary of fields: from pydantic import BaseModel, create_model from typing import Any def create_dynamic_model(name: str, fields: dict[str, Any]) -> BaseModel: return create_model(name, **fields) # Example Usage DynamicUserModel = create_dynamic_model('DynamicUser', {'name': (str, ...), 'age': (int, ...)}) # Now you can use this model in FastAPI from fastapi import FastAPI app = FastAPI() @app.post("/user") async def create_user(user: DynamicUserModel): return user
🌐
GitHub
github.com › pydantic › pydantic › issues › 5293
Create model by picking fields from another model · Issue #5293 · pydantic/pydantic
March 28, 2023 - from pydantic import BaseModel, create_model class User(BaseModel): id: int name: str email: str age: int def create_pydantic_subset(original_model: BaseModel, fields: list): subset_fields = {field_name: (field.type_, ...) for field_name, field in original_model.__fields__.items() if field_name in fields} return create_model(f'{original_model.__name__}Subset', **subset_fields) UserPatch = create_pydantic_subset(User, ['name', 'email'])
Author   djdylan2000
🌐
Pydantic
docs.pydantic.dev › latest › integrations › datamodel_code_generator
datamodel-code-generator - Pydantic Validation
The datamodel-code-generator project is a library and command-line utility to generate pydantic models from just about any data source, including:
🌐
GitHub
github.com › pydantic › pydantic › blob › main › docs › concepts › models.md
pydantic/docs/concepts/models.md at main · pydantic/pydantic
When using attributes to validate models, model instances will be created from both top-level attributes and deeper-nested attributes as appropriate. ... from pydantic import BaseModel, ConfigDict class PetCls: def __init__(self, *, name: str) -> None: self.name = name class PersonCls: def __init__(self, *, name: str, pets: list[PetCls]) -> None: self.name = name self.pets = pets class Pet(BaseModel): model_config = ConfigDict(from_attributes=True) name: str class Person(BaseModel): model_config = ConfigDict(from_attributes=True) name: str pets: list[Pet] bones = PetCls(name='Bones') orion = PetCls(name='Orion') anna = PersonCls(name='Anna', pets=[bones, orion]) anna_model = Person.model_validate(anna) print(anna_model) #> name='Anna' pets=[Pet(name='Bones'), Pet(name='Orion')]
Author   pydantic
🌐
Pydantic
pydantic.com.cn › en › concepts › models
Models - Pydantic documentation (en)
Unlike a call to __init__, a call ... corresponding to fields. Rather, said input data is simply ignored. Pydantic supports the creation of generic models to make it easier to reuse a common model structure....