Skip to content

Nested Pydantic Model from Dict

August 9, 202225 second read

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

from pydantic import BaseModelfrom typing import Dict,Listclass A(BaseModel):  key: str  value: strclass 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

Share this article

No Comments

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Next article
Previous article
Back To Top