1

I need to check key in MyDict - key must be in A_list, value is free. How can i do this?

from pydantic import BaseModel
from typing import List, Dict, Tuple
class Model(BaseModel):
 A_list: List[str]
 MyDict: Dict[str, str] # 1-str is A_list
asked Aug 10, 2021 at 9:26

1 Answer 1

1

You can use validators. They are class methods, so values (a dictionary) must be provided after your dictionary to retrieve already validated fields of your Model - in this case, A_list.

from pydantic import BaseModel, validator
from typing import List, Dict, Tuple
class Model(BaseModel):
 A_list: List[str]
 MyDict: Dict[str, str] # 1-str is A_list
 @validator("MyDict")
 def must_be_in_list(cls, thedict, values):
 for key in thedict.keys():
 if key not in values["A_list"]:
 raise ValueError(f"{key} not found in list!")
m1 = Model(A_list=["a"], MyDict={"a": 1}) # ok
m2 = Model(A_list=["a"], MyDict={"a": 1, "b": 2})
"""
Traceback (most recent call last):
 File "<input>", line 1, in <module>
 File "pydantic\main.py", line 406, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for Model
MyDict
 b not found in list! (type=value_error)
"""
answered Aug 10, 2021 at 9:45
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.