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

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.


addition, you can use __init method,

your_mode = YourMode(**your_dict)

There's no method for exactly that, but you can use create_model() to create a model if you know the field types.

Or there's datamodel-code-generator (separate package) which allows you to generate models from schema definitions.