Skip to content
Advertisement

Create a pydantic model with dynamic keys

I want to create a Pydantic model for this structure:

JavaScript

My first attempt was

JavaScript

But this raises an exception:

JavaScript

If i change Dict to dict, i don’t get the exception, but the resulting object yields an empty dict:

JavaScript

what am i doing wrong?

Advertisement

Answer

You have a typo in model declaration. Use a colon instead of the equal sign.

JavaScript

Then you can create a model instance:

JavaScript

You can find more information here: custom-root-types

Please also look at this section. Maybe you will find here some interesting stuff: dynamic-model-creation

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement