Skip to main content

How to Validate a Dictionary with model_validate in pydantic

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Data often arrives as a dictionary: from a JSON file, a YAML file or a web request. Model.model_validate(data) checks that dictionary against a pydantic model and gives you the model back. This guide validates a small dictionary with pydantic 2.14.4 on Python 3.15.2.

Syntax​

Syntax
<item> = <Model>.model_validate(<dictionary>)
PartWhat it means
<Model>A class that inherits from BaseModel
.model_validate(...)A class method: you call it on the class itself, not on an item
<dictionary>The data, with one key per field

pydantic's models guide says that with model_validate(), "data can be provided either as a dictionary, or as a model instance".

The Example​

A Point has x and y numbers. The data arrives as a dictionary in which y is text, "4", as values from a form often are.

Prerequisites​

  • pydantic in your project, for example with uv add pydantic. This guide uses pydantic 2.14.4 on Python 3.15.2.

Step 1: Write the Script​

from_dict.py
from pydantic import BaseModel


class Point(BaseModel):
x: int
y: int


data = {"x": 3, "y": "4"}
point = Point.model_validate(data)

print(point)
print(point.x + point.y)

The from_dict.py script in a macOS-style code window: a Point model with x and y integers, a data dictionary with y as the text "4", and Point.model_validate(data).

Step 2: Run It​

Terminal
uv run python from_dict.py
Output
x=3 y=4
7

The terminal after uv run python from_dict.py: x=3 y=4, then 7.

The dictionary became a Point, and "4" became the number 4, so x + y gave 7. The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Passing the dictionary to the constructor: Point({"x": 3, "y": 4})TypeError: BaseModel.__init__() takes 1 positional argument but 2 were givenUse Point.model_validate(data)
Passing something that isn't a dictionary, such as [3, 4]Input should be a valid dictionary or instance of Point [type=model_type, input_value=[3, 4], input_type=list]Give the values names: {"x": 3, "y": 4}

Troubleshooting​

SymptomLikely causeFix
[type=model_type ...]The data isn't a dictionary or a modelCheck what the file or request really returned

FAQ​

Is Point(**data) the same?​

For a plain dictionary, it gave the same result here: Point(**data) printed x=3 y=4. ** spreads the dictionary into keyword arguments. model_validate takes the dictionary itself, so it also works when you have a variable that could be a model instead.

Conclusion​

Point.model_validate({"x": 3, "y": "4"}) checked the dictionary and returned x=3 y=4. Use it whenever your data is already a dictionary, and keep the constructor for keyword arguments.

Additional Resources​

  • Validating data — model_validate and its JSON and string versions.
  • Models — everything about pydantic models.