Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Python dict to a Class object

I am looking for a simple way to directly convert a python dict to a custom object as follows, while not breaking intellisense. The result should not be read-only, it should behave just like a new object.

d = {
    "key1": 1,
    "key2": 2
}

class MyObject(object):
    key1 = None
    key2 = None

# convert to object o

# after conversion
# should be able to access the defined props
# should be highlighted by intellisense
print(o.key1)
# conversion back to dict is plain simple
print(o.__dict__)
like image 855
Alex Predescu Avatar asked Dec 10 '25 23:12

Alex Predescu


1 Answers

Your object has no fields, just class attributes. You need to create a __init__ method, some will call it a constructor but it is not actually a constructor as understood by other languages so lets avoid calling it like that.

class MyObject:
    def __init__(self, d=None):
        if d is not None:
            for key, value in d.items():
                setattr(self, key, value)

d = {
    "key1": 1,
    "key2": 2,
}

o = MyObject(d)

Note: the above code will try to set all key-value pairs in the dict to fields in the object. Some valid keys such as "key.1" will not be valid field names (it will actually be set but you will not be able to get it with o.key.1).

like image 198
Adirio Avatar answered Dec 13 '25 11:12

Adirio



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!