1 min read

Nested Pydantic Model from Dict

Nested Pydantic Model from Dict

Quick notes on how to instantiate a pydantic.BaseModel from a python Dictionary:

from pydantic import BaseModel
from typing import Dict,List


class A(BaseModel):
  key: str
  value: str


class B(BaseModel):
  id_: str
  a_list: Dict[str, List[A]]


x = {"id_": "asd", "a_list": {"dbz": [{"key": "goku", "value": "gohan"}]}}

b = B(**x)

print(b)
print(b.a_list)
print(b.a_list["dbz"][0].key)
print(b.a_list["dbz"][0].value)

# id_='asd' a_list={'dbz': [A(key='goku', value='gohan')]}
# {'dbz': [A(key='goku', value='gohan')]}
# goku
# gohan