0
0
FastapiHow-ToBeginner · 2 min read

FastAPI How to Convert Pydantic Model to Dict Easily

In FastAPI, you can convert a Pydantic model to a dictionary by calling the .dict() method on the model instance, like model_instance.dict().
📋

Examples

InputUser(name='Alice', age=30)
Output{"name": "Alice", "age": 30}
InputUser(name='Bob', age=None)
Output{"name": "Bob", "age": null}
InputUser(name='Eve', age=25, extra='ignored')
Output{"name": "Eve", "age": 25}
🧠

How to Think About It

To convert a Pydantic model to a dictionary, you simply use the built-in .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

1
Create or receive a Pydantic model instance.
2
Call the <code>.dict()</code> method on the model instance.
3
Use or return the resulting dictionary.
💻

Code

python
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
Output
{'name': 'Alice', 'age': 30}
🔍

Dry Run

Let's trace converting a User model instance with name 'Alice' and age 30 to a dictionary.

1

Create User instance

user = User(name='Alice', age=30)

2

Call .dict() method

user_dict = user.dict() # returns {'name': 'Alice', 'age': 30}

3

Use the dictionary

print(user_dict) outputs {'name': 'Alice', 'age': 30}

StepActionValue
1Create User instanceUser(name='Alice', age=30)
2Call .dict(){'name': 'Alice', 'age': 30}
3Print 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

json() method
python
user_json = user.json()  # returns JSON string like '{"name": "Alice", "age": 30}'
Returns a JSON string instead of a dictionary; useful if you want a JSON text output.
dict(exclude_unset=True)
python
user_dict = user.dict(exclude_unset=True)  # excludes fields not set explicitly
Useful to get only fields that were set, ignoring defaults.

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.

ApproachTimeSpaceBest 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
💡
Use .dict() to get a clean dictionary from your Pydantic model for easy JSON responses.
⚠️
Trying to use vars() or __dict__ on Pydantic models instead of the .dict() method, which may miss validation and aliases.