Pydantic Nested Dictionary
Pydantic is a library in Python that provides data validation and settings management using Python type hints.
When dealing with nested dictionaries in Pydantic, we can define models that reflect the structure and types of the nested dictionary.
Example:
from pydantic import BaseModel, ValidationError
from typing import Dict
class InnerModel(BaseModel):
value1: int
value2: str
class OuterModel(BaseModel):
nested_dict: Dict[str, InnerModel]
# Sample nested dictionary
nested_dictionary = {
"key1": {
"value1": 1,
"value2": "abc"
},
"key2": {
"value1": 2,
"value2": "def"
}
}
try:
# Parsing the nested dictionary into the OuterModel
outer_model = OuterModel.parse_obj(nested_dictionary)
# Accessing values using model structure
print(outer_model.nested_dict["key1"].value1) # Output: 1
print(outer_model.nested_dict["key2"].value2) # Output: "def"
except ValidationError as e:
print(e.json())
In this example, we create two Pydantic models: InnerModel and OuterModel. InnerModel defines the fields value1 and value2, while OuterModel includes a nested_dict field of type Dict[str, InnerModel]. We then create a sample nested dictionary and parse it into the OuterModel using the parse_obj method.
We can access the values of the nested dictionary using the model structure, such as outer_model.nested_dict[“key1”].value1 and outer_model.nested_dict[“key2”].value2.
Note: The code snippet provided demonstrates how to work with nested dictionaries using Pydantic. Remember to include the necessary import statements and handle potential validation errors when working with real-world applications.