Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update dataclass fields from a dict in python

How can I update the fields of a dataclass using a dict?

Example:

@dataclass
class Sample:
    field1: str
    field2: str
    field3: str
    field4: str

sample = Sample('field1_value1', 'field2_value1', 'field3_value1', 'field4_value1')
updated_values = {'field1': 'field1_value2', 'field3': 'field3_value2'}

I want to do something like

sample.update(updated_values)
like image 829
Nagabhushan S N Avatar asked Mar 23 '26 18:03

Nagabhushan S N


1 Answers

One way is to make a small class and inherit from it:

class Updateable(object):
    def update(self, new):
        for key, value in new.items():
            if hasattr(self, key):
                setattr(self, key, value)

@dataclass
class Sample(Updateable):
    field1: str
    field2: str
    field3: str
    field4: str

You can read this if you want to learn more about getattr and setattr

like image 112
bb1950328 Avatar answered Mar 26 '26 10:03

bb1950328



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!