Pydantic dynamic key

Pydantic Dynamic Key

Pydantic is a Python library that provides runtime validation and parsing of data structures, ensuring their validity and consistency. It is widely used for creating data validation and settings management in your Python applications.

When it comes to dynamic keys in Pydantic, it means accepting or validating keys that are not known or predefined. This can be useful when dealing with data structures that may have varying keys, such as dictionaries or JSON objects.

Let’s take a look at an example to understand this concept better. Consider a scenario where you have a JSON object with dynamic key-value pairs, and you want to validate it using Pydantic.

    
      from pydantic import BaseModel, Field

      class DynamicKeyModel(BaseModel):
          __root__: dict[str, str]

      # Test data
      json_data = {
          "key_1": "value_1",
          "key_2": "value_2",
          "key_3": "value_3"
      }

      # Validate the data
      model = DynamicKeyModel.parse_obj(json_data)

      # Access the validated data
      for key, value in model.dict().items():
          print(f"{key}: {value}")
    
  

In the code above, we define a Pydantic model named DynamicKeyModel with a single attribute named __root__. The __root__ attribute is of type dict[str, str], which represents a dictionary with string keys and string values. This allows us to accept any dynamic key-value pairs in the JSON object.

We then create some test data in the form of a JSON object with three key-value pairs. We use the parse_obj method of the model to validate the JSON data. If the data does not match the expected structure, Pydantic will raise a validation error.

Finally, we access the validated data by calling the dict() method on the model instance. This returns the validated data as a Python dictionary, which we can iterate over and process as needed.

Leave a comment