["python","pydantic"]
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
In Pydantic 2, you can use MyModel.model_validate(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. If you're Pydantic 1, the method is parse_obj instead.