Pydantic 1.x (old answer)

The current version of pydantic does not support creating jsonable dict straightforwardly. But you can use the following trick:

Note: This is a suboptimal solution

class Model(BaseModel):
    the_id: UUID = Field(default_factory=uuid4)

print(json.loads(Model().json()))
{'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}

Or more efficiently by means of orjson

orjson.loads(Model().json())

Pydantic 2

There is the model_dump() method accepting the mode parameter.

mode: Literal['json', 'python'] | str = 'python'

If mode is 'json', the dictionary will only contain JSON serializable types.

If mode is 'python', the dictionary may contain any Python objects.

class Model(BaseModel):
    the_id: UUID = Field(default_factory=uuid4)

print(Model().model_dump(mode='json'))
# {'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}
Answer from alex_noname on Stack Overflow
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › exporting_models
Exporting models - Pydantic
In addition to the explicit arguments exclude and include passed to dict, json and copy methods, we can also pass the include/exclude arguments directly to the Field constructor or the equivalent field entry in the models Config class: ... from pydantic import BaseModel, Field, SecretStr class User(BaseModel): id: int username: str password: SecretStr = Field(..., exclude=True) class Transaction(BaseModel): id: str user: User = Field(..., exclude={'username'}) value: int class Config: fields = {'value': {'exclude': True}} t = Transaction( id='1234567890', user=User( id=42, username='JohnDoe', password='hashedpassword' ), value=9876543210, ) print(t.dict()) #> {'id': '1234567890', 'user': {'id': 42}}
Discussions

Generating json/dictionary from pydantic model
If you mean to generate it from an object, then use model.model_dump(...). It also provides options to choose which fields should be included https://docs.pydantic.dev/latest/concepts/serialization/ If you want to create the dict from the class itself, to for example document the defaults, then first create instance of the class and then use model_dump on that instance. More on reddit.com
🌐 r/learnpython
4
1
January 14, 2024
Model - coerce string to dict for field
If im retrieving data as a dict but there are some fields in the dict that are nested dicts. if a field is set to be type dict and the data coming in is a str for that field what is the best way to... More on github.com
🌐 github.com
1
1
python - How to write a Pydantic model to accept a Dictionary of Dictionaries - Stack Overflow
The code below is modified from the Pydantic documentation I would like to know how to change BarModel and FooBarModel so they accept the input assigned to m1. I have tried using __root__ and syntax such as Dict[str, BarModel] but have been unable to find the magic combination. More on stackoverflow.com
🌐 stackoverflow.com
python - Generate pydantic model from a dict - Stack Overflow
Future readers might find this answer helpful, when dealing with populating a Pydantic model, using either previously unknown data or data that is already known to be valid. ... In Pydantic 2, you can use MyModel.model_validate(my_dict) to generate a model from a dictionary. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pydantic
docs.pydantic.dev › 2.3 › usage › types › dicts_mapping
Dicts and Mapping - Pydantic
from pydantic import BaseModel, ValidationError class Model(BaseModel): x: dict m = Model(x={'foo': 1}) print(m.model_dump()) #> {'x': {'foo': 1}} try: Model(x='test') except ValidationError as e: print(e) """ 1 validation error for Model x Input should be a valid dictionary [type=dict_type, input_value='test', input_type=str] """
🌐
Pydantic
docs.pydantic.dev › latest › concepts › serialization
Serialization - Pydantic Validation
When using the Python mode, Pydantic models (and model-like types such as dataclasses) (1) will be (recursively) converted to dictionaries.
🌐
Netlify
field-idempotency--pydantic-docs.netlify.app › usage › exporting_models
Exporting models - pydantic
pydantic models can also be converted to dictionaries using dict(model), and you can also iterate over a model's field using for field_name, value in model:. With this approach the raw field values are returned, so sub-models will not be converted to dictionaries.
Find elsewhere
Top answer
1 of 2
13

If all you're trying to do is have a dictionary of BarModel's in another model, this answers your question:

from typing import Dict
from pydantic import BaseModel

class BarModel(BaseModel):
    whatever: float
    foo: str

class FooBarModel(BaseModel):
    dictionaries: Dict[str, BarModel]

m1 = FooBarModel(dictionaries={
    'a': {'whatever': 12.3, 'foo': 'hello'},
    'b': {'whatever': 12.4, 'foo': 'bye'}
}

print(m1.dict())
2 of 2
5

You already found your magic combination, you haven't realized it yet.

from pydantic import BaseModel
from typing import Dict

class BarModel(BaseModel):
    whatever: float
    foo: str

class FooBarModel(BaseModel):
    banana: str
    bar: Dict[str, BarModel]


m1 = FooBarModel(banana="a", bar={
  'a':{'whatever': 12.3, 'foo':'hello'},
  'b':{'whatever': 12.4, 'foo':'bye'}
})

assert m1.dict() == {'banana': 'a', 'bar': {'a': {'whatever': 12.3, 'foo': 'hello'}, 'b': {'whatever': 12.4, 'foo': 'bye'}}}

This runs without any errors.

Note that we still have banana, if you want to discard it, simply delete.

If you wanted use pure typing and some static analyzer your examples would evaluate to this

from typing import Dict, Union
m = FooBarModel(banana='a', bar={'whatever': 12.3, 'foo':'hello'})


m: Dict[str, Union[str, Dict[str, Union[float, str]]]]

But what you want is actually this

from typing import Dict, Union

m1 = FooBarModel({
  'a':{'whatever': 12.3, 'foo':'hello'},
  'b':{'whatever': 12.4, 'foo':'bye'}
})

m1: Dict[str, Union[str, Dict[str, Dict[str, Union[float, str]]]]]
🌐
PyPI
pypi.org › project › pydantic-dict
pydantic-dict
JavaScript is disabled in your browser. Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Linux Hint
linuxhint.com › convert-pydantic-model-dict-step-by-step-guide
How to Convert Pydantic Model to Dict: A Step-by-Step Guide
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
FastAPI
fastapi.tiangolo.com › tutorial › extra-models
Extra Models - FastAPI
Pydantic models have a .model_dump() method that returns a dict with the model's data.
🌐
OpenAI Developer Community
community.openai.com › api › bugs
Pydantic with Dict not working - Bugs - OpenAI Developer Community
December 7, 2024 - Trying to get response like this: {“1”: “first”, “2”: “second”, …} but using dict somehow doesn’t work. Am I doing something wrong? class MyObject(BaseModel): my_values: Dict[str, str] response = client.beta.chat.completions.parse( model="gpt-4o", messages=[ {"role": "system", ...
🌐
GitHub
github.com › pydantic › pydantic › discussions › 4597
Construct from dict/mapping. · pydantic/pydantic · Discussion #4597
This is actually much like plain python dicts behave with different arguments. Disadvantages: I could not imagine any, since plain pydantic models do not accept positional arguments, so any existing code would not break.
Author   pydantic
🌐
Blue Book
lyz-code.github.io › blue-book › coding › python › pydantic_exporting
Pydantic exporting models - The Blue Book
pydantic models can also be converted to dictionaries using dict(model), and you can also iterate over a model's field using for field_name, value in model:. With this approach the raw field values are returned, so sub-models will not be converted to dictionaries.
🌐
Helpmanual
pydantic-docs.helpmanual.io › usage › exporting_models
Serialization - Pydantic Validation
In addition to the explicit arguments exclude and include passed to dict, json and copy methods, we can also pass the include/exclude arguments directly to the Field constructor or the equivalent field entry in the models Config class: ... from pydantic import BaseModel, Field, SecretStr class User(BaseModel): id: int username: str password: SecretStr = Field(..., exclude=True) class Transaction(BaseModel): id: str user: User = Field(..., exclude={'username'}) value: int class Config: fields = {'value': {'exclude': True}} t = Transaction( id='1234567890', user=User( id=42, username='JohnDoe', password='hashedpassword' ), value=9876543210, ) print(t.dict()) #> {'id': '1234567890', 'user': {'id': 42}}
🌐
GitHub
github.com › pydantic › pydantic › discussions › 2948
BaseModel that acts as a dict · pydantic/pydantic · Discussion #2948
It is interesting thing to play with, but I do not see practical cases of such pattern. from pydantic import BaseModel from pydantic.generics import GenericModel from typing import Dict, TypeVar, Generic DataX = TypeVar('DataX') DataY = TypeVar('DataY') class DictModel(GenericModel, Generic[DataX, DataY]): __root__: Dict[DataX, DataT] def __getitem__(self, key): return self.__root__[key] def __setitem__(self, key, value): self.__root__[key] = value def __delitem__(self, key): del self.__root__[key] DictModelStr = DictModel[str, str] item = DictModelStr(__root__={"lol": "kek", "foo": "bar"}) print(item["lol"]) # kek item["new"] = 1 print(item.__root__) # {'lol': 'kek', 'foo': 'bar', 'new': 1} del item["new"] print(item.__root__) # {'lol': 'kek', 'foo': 'bar'}
Author   pydantic
🌐
Finxter
blog.finxter.com › 5-effective-ways-to-convert-python-dict-to-pydantic-model
5 Effective Ways to Convert Python Dict to Pydantic Model – Be on the Right Side of Change
February 21, 2024 - The construct method is another Pydantic functionality that allows you to create a model without validation. This is useful for performance-critical situations where you’re certain the data is already valid. ... from pydantic import BaseModel class User(BaseModel): name: str age: int user_dict = {"name": "Bob", "age": 25} user_model = User.construct(**user_dict) print(user_model)
🌐
Bryan Anthonio
bryananthonio.com › blog › pydantic-custom-dictionary-types
Custom Dictionary Types in Pydantic
June 19, 2024 - I wanted to find an easier way to do this. After digging through the documentation, I discovered that I could achieve my goals using custom root types. Using the RootModel class, we can rewrite the AnimalDict class as follows: ... from pydantic import RootModel from typing import Dict class AnimalDict(RootModel): root: Dict[AnimalSpecies, AnimalData] def __getitem__(self, key: AnimalSpecies): return self.root[key] def __setitem__(self, key: AnimalSpecies, value: AnimalData): self.root[key] = value @model_validator(mode="after") def check_dictionary_types(self) -> Self: keys = self.root.keys() for key in keys: if not isinstance(key, AnimalSpecies): raise TypeError(f"Dictionary key {key} isn't of type AnimalSpecies") value = self.root[key] if not isinstance(value, AnimalData): raise TypeError( f"The object {value} bound to key {key} isn't of type AnimalData" ) return self
🌐
GitHub
github.com › pydantic › pydantic › issues › 5711
Pydantic frozen models as keys for dictionaries · Issue #5711 · pydantic/pydantic
May 7, 2023 - Sort of a minimal example to illustrate what I'm after: from pydantic import BaseModel class A(BaseModel): a: str class Config: frozen = True class B(BaseModel): z: dict[A, float] b = B(z={A(a='a'): 1.0}) json_b = b.model_dump_json() # works b.model_validate_json(json_b) # fails
Author   bramjochems