Some text some message..
Back Pydantic: BaseModel provides .dict() support 22 May, 2025

In Pydantic, BaseModel provides .dict() support, which allows you to easily convert a model instance into a Python dictionary.

This is useful when you need to serialize the data, work with native Python types, or pass data to other libraries (like databases, APIs, etc.).


✅ Syntax

model_instance.dict(*, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False)

📦 Simple Example

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str
    email: str

user = User(id=1, name="Abhi", email="abhi@example.com")
print(user.dict())

Output:

{'id': 1, 'name': 'Abhi', 'email': 'abhi@example.com'}

🎯 Why .dict() is useful

  • Converts model data to native dict

  • Makes it easy to:

    • Return JSON responses

    • Store in databases

    • Send over APIs


🔧 Advanced Usage

1. include & exclude

user.dict(include={"id", "email"})
# {'id': 1, 'email': 'abhi@example.com'}

user.dict(exclude={"email"})
# {'id': 1, 'name': 'Abhi'}

2. exclude_unset

Includes only fields explicitly set by the user.

class Product(BaseModel):
    name: str
    price: float = 99.99
    in_stock: bool = True

p = Product(name="Pen")

p.dict()
# {'name': 'Pen', 'price': 99.99, 'in_stock': True}

p.dict(exclude_unset=True)
# {'name': 'Pen'}

3. exclude_none

Skips fields with None values.

class Person(BaseModel):
    name: str
    age: int = None

p = Person(name="John")

p.dict(exclude_none=True)
# {'name': 'John'}

📌 Real-World Use Case

Sending response in FastAPI:

@app.get("/user", response_model=User)
def get_user():
    user = User(id=1, name="Abhi", email="abhi@example.com")
    return user.dict()  # returns as dict which FastAPI converts to JSON

📝 Summary Table

Option Description
include Include only these fields
exclude Exclude specific fields
exclude_unset Exclude fields not explicitly set
exclude_defaults Exclude fields set to their default value
exclude_none Exclude fields that are None
by_alias Use alias names (if any) instead of field names