Pydantic create model from dict

pydantic: Create Model from Dict

Pydantic is a library in Python that allows you to define strict, type-annotated data structures, known as models. These models can be used to validate and parse data from various sources, including dictionaries.

To create a Pydantic model from a dictionary, you need to define a new class that inherits from the `pydantic.BaseModel` class. Each attribute in the model corresponds to a key-value pair in the dictionary.

Here’s an example of creating a Pydantic model from a dictionary:


import pydantic

class Person(pydantic.BaseModel):
    name: str
    age: int
    email: str

data = {
    "name": "John Doe",
    "age": 30,
    "email": "john.doe@example.com"
}

person = Person(**data)
print(person)
  

In the code above, we define a `Person` model with three attributes: `name`, `age`, and `email`. We then create a dictionary `data` with the corresponding key-value pairs. By passing `**data` as arguments to the `Person` class, we initialize an instance of the model named `person`.

Pydantic will automatically validate the data based on the model’s type annotations. If any attribute is missing or of the wrong type, it will raise a `ValidationError`.

You can access the individual attributes of the `person` object just like any other Python class:


print(person.name)
print(person.age)
print(person.email)
  

The output will be:


John Doe
30
john.doe@example.com
  

By using Pydantic models, you can ensure that your data is properly validated and has the expected structure.

Leave a comment