pydantic generate model from dict

Dillon Miller picture Dillon Miller · Jun 8, 2020 · Viewed 9.2k times · Source

I've only recently starting glansing over the documentation of pydantic but I don't see a straight-forward approach to generating models from dict object. Is there a way to generate one that I can then retrieve and save for later?

Here is a sample of the data I have.

{
    'id': '424c015f-7170-4ac5-8f59-096b83fe5f5806082020',
    'contacts': [{
        'displayName': 'Norma Fisher',
        'id': '544aa395-0e63-4f9a-8cd4-767b3040146d'
    }],
    'startTime': '2020-06-08T09:38:00+00:00'
}

Expecting a model similar to ...

class NewModel(BaseModel):
    id: str
    contacts: list
    startTime: str

Answer

Alex King picture Alex King · Oct 23, 2020

You can use MyModel.parse_obj(my_dict) to generate a model from a dictionary. According to the documentation

this is very similar to the __init__ method of the model, except it takes a dict rather than keyword arguments.