Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate pydantic model from a dict

Is there a straight-forward approach to generate a Pydantic model from a dictionary?

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
like image 995
Dillon Miller Avatar asked Jun 08 '20 17:06

Dillon Miller


2 Answers

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.

like image 188
Alex King Avatar answered Nov 07 '22 13:11

Alex King


You can also use its __init__ method:

your_mode = YourMode(**your_dict)
like image 20
xiaopo Avatar answered Nov 07 '22 12:11

xiaopo