Skip to content
Advertisement

Create a pydantic model with dynamic keys

I want to create a Pydantic model for this structure:

{
  "key-1": ["value-1", "value-2"],
  "key-2": ["value-3"],
  "key-3": []
}

My first attempt was

class MyModel(BaseModel):
  __root__ = Dict[str, List[str]]

  @root_validator(pre=True)
  def validate_all_the_things(cls, values):
    # check if keys and values match some regexes

But this raises an exception:

RuntimeError: no validator found for <class 'typing._GenericAlias'>, see `arbitrary_types_allowed` in Config

If i change Dict to dict, i don’t get the exception, but the resulting object yields an empty dict:

>>> MyModel(**{"key-1": ["value-1"]}).dict()
{}

what am i doing wrong?

Advertisement

Answer

You have a typo in model declaration. Use a colon instead of the equal sign.

from typing import List, Dict
from pydantic import BaseModel

class MyModel(BaseModel):
    __root__: Dict[str, List[str]]

Then you can create a model instance:

>>> my_instance = MyModel.parse_obj({"key-1": ["value-1"]})
>>> my_instance.dict()
{'__root__': {'key-1': ['value-1']}}

You can find more information here: custom-root-types

Please also look at this section. Maybe you will find here some interesting stuff: dynamic-model-creation

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement