Dave Hwang
Dave Hwang

Reputation: 59

How to validate a complex nested data structure with Pydantic?

I had complex and nested data structure like below:

{   0: {   0: {'S': 'str1', 'T': 4, 'V': 0x3ff},
           1: {'S': 'str2', 'T': 5, 'V': 0x2ff}},
    1: {   0: {'S': 'str3', 'T': 8, 'V': 0x1ff},
           1: {'S': 'str4', 'T': 7, 'V': 0x0ff}},
......
}

It's a 2D dictionary basically. The innermost dict follows {Str: str, str:int, str:int}, while its outer dict always has integer as the key to index.

Is there a way for Pydantic to validate the data-type and data structure? I mean if someone changes the data with a string as a key to the outer dict, the code should prompt an error. Or if someones tweaks the inner dict with putting 'V' value to a string, a checker needs to complain about it.

I am new to Pydantic, and found it always requires a str-type field for any data... Any ideas?

Upvotes: 5

Views: 5138

Answers (1)

alex_noname
alex_noname

Reputation: 32163

You could use Dict as custom root type with int as key type (with nested dict). Like so:

from pydantic import BaseModel, StrictInt
from typing import Union, Literal, Dict

sample = {0: {0: {'S': 'str1', 'T': 4, 'V': 0x3ff},
              1: {'S': 'str2', 'T': 5, 'V': 0x2ff}},
          1: {0: {'S': 'str3', 'T': 8, 'V': 0x1ff},
              1: {'S': 'str4', 'T': 7, 'V': 0x0ff}}
          }


# innermost model
class Data(BaseModel):
    S: str
    T: int
    V: int


class Model(BaseModel):
    __root__: Dict[int, Dict[int, Data]]


print(Model.parse_obj(sample))

Upvotes: 5

Related Questions