reza
reza

Reputation: 6358

How do I copy class attributes from a dict?

using python 3.6 on Mac

I have the following class and I want to instantiate it from a dict

from pydantic import BaseModel
class MyModel(BaseModel):
    brand: Optional[str]

I need to copy attributes from a dict

def copy_from_make_model(self, data: dict) -> None:
    self.brand = data['brand']

what happens it the dict does not have a brand key?

Do I need to check for brand key existence for each of MyModel attributes?

What is the Pythonic way to do this?

Upvotes: 0

Views: 165

Answers (2)

Josewails
Josewails

Reputation: 580

Rather than creating your own function to do the conversion, you could use the already Pydantic's dict method to accomplish the same.

class MyModel(BaseModel):
    brand: Optional[str]


my_model = MyModel(brand="test brand")
my_model_dict = my_model.dict()
print(my_model_dict)

This will give the following result.

{'brand': 'test brand'}

Upvotes: 0

user17852071
user17852071

Reputation:

This will set brand="" if the data dict doesn't have a brand key.

def copy_from_make_model(self, data):
    self.brand = data.get("brand", "")

Upvotes: 1

Related Questions