‘model.dict()’ function return a dictionary of model fields.
Example
emp1 = Employee(id = 1, name = 'Krishna', age = 23)
empDict = emp1.dict()
get_dict_of_model_fields.py
from pydantic import BaseModel, ValidationError
class Employee(BaseModel):
id: int
name: str
age: int
emp1 = Employee(id = 1, name = 'Krishna', age = 23)
empDict = emp1.dict()
print('empDict ' + str(empDict))
print('dict(emp1) ' + str(dict(emp1)))
Output
empDict {'id': 1, 'name': 'Krishna', 'age': 23} dict(emp1) {'id': 1, 'name': 'Krishna', 'age': 23}
‘dict’ method can take arguments include, exclude, by_alias, exclude_unset, exclude_defaults and exclude_none. Below table summarizes each argument in detail.
Argument |
Description |
include |
Specifies fields to include in the returned dictionary |
exclude |
Specifies fields to exclude from the returned dictionary |
by_alias |
Specify field aliases should be used as keys in the returned dictionary |
exclude_unset |
Specifies whether fields which were not explicitly set when creating the model should be excluded from the returned dictionary. default False. |
exclude_defaults |
Specifies whether fields which are equal to their default values (whether set or otherwise) should be excluded from the returned dictionary. default False |
exclude_none |
Specifies whether fields which are equal to None should be excluded from the returned dictionary. Default to False. |
Example
empDict1 = emp1.dict()
empDict2 = emp1.dict(include= {'id', 'name'})
empDict3 = emp1.dict(exclude= {'age'})
dict_method_1.py
from pydantic import BaseModel, ValidationError
class Employee(BaseModel):
id: int
name: str
age: int
emp1 = Employee(id = 1, name = 'Krishna', age = 23)
empDict1 = emp1.dict()
empDict2 = emp1.dict(include= {'id', 'name'})
empDict3 = emp1.dict(exclude= {'age'})
print('empDict1 -> ' + str(empDict1))
print('empDict2 -> ' + str(empDict2))
print('empDict3 -> ' + str(empDict3))
Output
empDict1 -> {'id': 1, 'name': 'Krishna', 'age': 23} empDict2 -> {'id': 1, 'name': 'Krishna'} empDict3 -> {'id': 1, 'name': 'Krishna'}
Using dict() method
You can convert a pydantic model to dictionary using dict method.
Example
emp1 = Employee(id = 1, name = 'Krishna', age = 23)
emp1Dict = dict(emp1)
dict_method_2.py
from pydantic import BaseModel, ValidationError
class Employee(BaseModel):
id: int
name: str
age: int
emp1 = Employee(id = 1, name = 'Krishna', age = 23)
emp1Dict = dict(emp1)
print('emp1 -> ' + str(emp1))
print('emp1Dict -> ' + str(emp1Dict))
Output
emp1 -> id=1 name='Krishna' age=23 emp1Dict -> {'id': 1, 'name': 'Krishna', 'age': 23}
fantastic blog.
ReplyDeleteEasy and clearly explained.