how convert list of dict to list of pydantic models
- User
how convert list of dict to list of pydantic models
- Assistant
To convert a list of dictionaries into a list of Pydantic models, you'll need to follow these general steps:
-
Define a Pydantic Model: Create a Pydantic model that corresponds to the structure of the dictionaries in your list.
-
Instantiate the Pydantic Model: Loop through the list of dictionaries and instantiate the Pydantic model for each dictionary.
Here’s an example to demonstrate these steps:
from pydantic import BaseModel from typing import List # Step 1: Define your Pydantic model class ItemModel(BaseModel): name: str price: float in_stock: bool # Example list of dictionaries item_dicts = [ {"name": "Item A", "price": 12.99, "in_stock": True}, {"name": "Item B", "price": 23.50, "in_stock": False}, {"name": "Item C", "price": 9.99, "in_stock": True}, ] # Step 2: Convert list of dicts to list of Pydantic models items: List[ItemModel] = [ItemModel(**item_dict) for item_dict in item_dicts] # Print converted items for item in items: print(item) -