To convert a Pydantic model to a dictionary, you can use the “dict()” method on a model instance. This method instantly transforms your structured data into a format that’s easy to manipulate and share.
Converting a Pydantic Model to a Dictionary
This example demonstrates the process of creating a Pydantic model class, instantiating it with attribute values and then converting the instance to a dictionary.
Let’s understand the procedure step by step.
To implement the example, we must first import the Pydantic library into our project.
The script starts by importing the “BaseModel” class from the Pydantic module. This class generates the Pydantic models that define the organized data structures accompanied by validation and parsing functionalities.
After importing the required module, we create a structure of the Pydantic model class.
Name: str
Age: int
Country: str
Here, we define a new class named “Person”, inheriting from “BaseModel”. This class represents a data structure that is expected to have specific features. Then, we specify three attributes of the “Person” class, and they are defined using the class-level variables. In this case, the “Name”, “Age”, and “Country” are the attributes of the “Person” class. We associate each attribute with a specific data type: “str”, “int”, and “str”, respectively.
Now that the structure of the model is defied, we create an instance of the “Person” class.
In this line of code, “p_instance” is the variable name that is chosen to store the instance of the “Person” class that we’re creating. The “Person” refers to the “Person” class that we defined earlier using the “BaseModel” as the base class. Then, the code has (Name=”Alexander”, Age=35, Country=”England”) part which is called the “constructor parameters”. It’s used to provide the values for the attributes of the “Person” class. We assign each attribute with a value using the “attribute_name=value” syntax.
In this constructor part, we assign the “Alexander” value to the “Name” attribute, the value of 35 to the “Age” attribute, and the “England” value is assigned to the “Country” attribute of the “Person” instance.
To sum up, this line of code creates an instance of the “Person” class with specific attribute values. The “p_instance” variable now holds an instance of the “Person” class with the “Name”, “Age”, and “Country” attributes set to “Alexander”, 35, and “England”, respectively. We can use this instance to access and manipulate the data associated with a person’s information.
Now, we build an illustration of the “Person” class. We will see how to convert this instance to a dictionary using the “dict()” method.
By invoking the “dict()” function, we convert the instance to a dictionary in the following line of code:
Here, “p_dict” is the variable name that we choose to store the resulting dictionary that we get from the conversion process. The “p_instance” variable stores an instance of the “Person” class that we created earlier. With that, we invoke the “dict()” method on the “p_instance” object. Calling this method converts the specified instance to a dictionary representation.
When we call the “dict()” method on a Pydantic model instance like “p_instance”, it converts the instance’s attributes and their corresponding values into a dictionary. The resulting dictionary is assigned to the “p_dict” variable.
The complete code for observation is provided here:
class Person(BaseModel):
Name: str
Age: int
Country: str
p_instance = Person(Name="Alexander", Age=35, Country="England")
p_dict = p_instance.dict()
Running this whole code results in the following output:
We successfully converted an instance of the model class to a dictionary.
The code in this example demonstrates how the Pydantic models can be used to define the structured data and how the instances of those models can be conveniently converted to dictionaries for various purposes.
After converting a Pydantic model to a dictionary, we gain the ability to manipulate the resulting data representation using a range of available options. These options provide precise control over which fields are included or excluded from the dictionary, tailoring the data to our needs.
We will demonstrate some of the options that could help in refining the dictionary to match the specific use cases.
Excluding the Default Values in the Resultant Dictionary
Here, we will see how to convert a Pydantic model instance to a dictionary while excluding the fields with default values.
In this line of code, “p_instance” is a Pydantic model instance that represents the data, and “p_dict” is a resulting dictionary. When we pass “exclude_unset=True” as an argument to the “dict()” method, it tells Pydantic to ignore the attributes from the dictionary that have values that are equal to their default values. This is useful to generate the relevant representation of the data.
For example, if you have a Pydantic model with a default value of 0 for an attribute, and that attribute is not explicitly set when creating an instance, using “exclude_unset=True” excludes that attribute from the resulting dictionary.
Here is the complete code:
class Person(BaseModel):
Name: str
Age: int
Country: str
p_instance = Person(Name="Alexander", Age=35, Country="England")
p_dict = p_instance.dict(exclude_unset=True)
Excluding and Including the Specific Fields in the Resultant Dictionary
We can also exclude specific fields while converting the model instance to a dictionary that we do not need in the resultant dictionary.
The code to this is as follows:
In this script, “p_instance” is an instance of a Pydantic model and “p_dict” is a dictionary that will be created. By calling the “dict()” method with the “exclude={“Country”}” argument, the code generates a “p_dict” dictionary from the “p_instance” model instance, excluding the “Country” attribute.
The complete code is:
class Person(BaseModel):
Name: str
Age: int
Country: str
p_instance = Person(Name="Alexander", Age=35, Country="England")
p_dict = p_instance.dict(exclude={"Country"})
This results in a dictionary representation of the data without the excluded attribute.
Similarly, we can specify which fields we want to include in the output dictionary using the “include” argument in the “dict()” method.
By applying the “dict()” method with the include={“Name”} argument, the code generates a dictionary (p_dict) from the model instance (p_instance), containing only the specified field (Name). This allows for the selective inclusion of data attributes in the resulting dictionary, focusing solely on the “Name” attribute in this case.
The code for observation is:
class Person(BaseModel):
Name: str
Age: int
Country: str
p_instance = Person(Name="Alexander", Age=35, Country="England")
p_dict = p_instance.dict(include={"Name"})
The generated output is as follows:
Conclusion
Converting a Pydantic model to a dictionary is a simple and easy process. This article provided you with a step-by-step guide for doing the conversion. We used the “dict()” method to convert the model to the dictionary. Moreover, after getting the converted dictionary, certain options can be applied to manipulate the dictionary to match the specific requirements. We demonstrated the utilization of some options in the created example.