FastAPI How to Convert Pydantic Model to Dict Easily
.dict() method on the model instance, like model_instance.dict().Examples
How to Think About It
.dict() method that Pydantic provides. This method returns all the model's data as a plain Python dictionary, which is easy to use or send as JSON in FastAPI responses.Algorithm
Code
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class User(BaseModel): name: str age: int | None = None @app.get("/user_dict") def get_user_dict(): user = User(name="Alice", age=30) user_dict = user.dict() print(user_dict) # {'name': 'Alice', 'age': 30} return user_dict
Dry Run
Let's trace converting a User model instance with name 'Alice' and age 30 to a dictionary.
Create User instance
user = User(name='Alice', age=30)
Call .dict() method
user_dict = user.dict() # returns {'name': 'Alice', 'age': 30}
Use the dictionary
print(user_dict) outputs {'name': 'Alice', 'age': 30}
| Step | Action | Value |
|---|---|---|
| 1 | Create User instance | User(name='Alice', age=30) |
| 2 | Call .dict() | {'name': 'Alice', 'age': 30} |
| 3 | Print dictionary | {'name': 'Alice', 'age': 30} |
Why This Works
Step 1: Pydantic Model Holds Data
The Pydantic model stores data in attributes like name and age.
Step 2: Use .dict() to Extract Data
Calling .dict() converts the model's data into a plain Python dictionary.
Step 3: Dictionary is Easy to Use
The dictionary can be used directly in FastAPI responses or for other processing.
Alternative Approaches
user_json = user.json() # returns JSON string like '{"name": "Alice", "age": 30}'user_dict = user.dict(exclude_unset=True) # excludes fields not set explicitly
Complexity: O(n) time, O(n) space
Time Complexity
The .dict() method iterates over all fields in the model, so it runs in linear time relative to the number of fields.
Space Complexity
It creates a new dictionary holding all field data, so space usage is linear with the number of fields.
Which Approach is Fastest?
Using .dict() is the fastest and safest way to convert a Pydantic model to a dictionary compared to manual methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| .dict() | O(n) | O(n) | Safe, full dict conversion |
| .json() | O(n) | O(n) | JSON string output |
| dict(exclude_unset=True) | O(n) | O(n) | Partial dict with set fields only |
.dict() to get a clean dictionary from your Pydantic model for easy JSON responses.vars() or __dict__ on Pydantic models instead of the .dict() method, which may miss validation and aliases.