Pydantic model to csv

Pydantic model to CSV

To convert a Pydantic model into a CSV file, you can make use of the pandas library in Python. Here’s an example of how you can accomplish this:


    from pydantic import BaseModel
    import pandas as pd
    
    class Person(BaseModel):
        name: str
        age: int
        email: str
    
    data = [
        {"name": "John", "age": 30, "email": "john@example.com"},
        {"name": "Jane", "age": 28, "email": "jane@example.com"},
        {"name": "Bob", "age": 35, "email": "bob@example.com"}
    ]
    
    people = [Person(**item) for item in data]
    
    df = pd.DataFrame([person.dict() for person in people])
    df.to_csv("people.csv", index=False)
  

In the above example, we define a Pydantic model called Person with three attributes: name, age, and email. We create a list of dictionaries representing the data we want to convert to CSV. Then, we create instances of the Person model from each dictionary using the **item unpacking syntax.

Next, we convert the list of Pydantic models into a pandas DataFrame by calling the person.dict() method on each person. This returns a dictionary representation of the person object. We pass this list of dictionaries to the DataFrame constructor of pandas. Finally, we use the to_csv method of the DataFrame to save it as a CSV file named people.csv.

Running this code will generate a CSV file with the following contents:


    name,age,email
    John,30,john@example.com
    Jane,28,jane@example.com
    Bob,35,bob@example.com
  

Each attribute of the Pydantic model is converted into a column in the CSV file, and each instance of the model is represented as a row.

Leave a comment