Sunday, April 25, 2021

Convert python dictionary to object

Consider having json response from REST service stored internally in dictionary object. Now, following code converts content of the dictionary to instace of class Test.

Keep in mind though it's just simple demonstration. Enhancement in form of data validation might be required!


from collections import namedtuple

class Test:
    def __init__(self, name : str, description : str, float_number : float): 
        self.name, self.descrition, self.float_number  = name, description, float_number

    def __repr__(self) -> str:
        return f"Test class data: name='{self.name}', description='{self.descrition}', number={self.float_number}"

paramDict = dict(name="Name Property Value", description="Description Property Value", float_number=102.0036)

tstInstance = Test(*(namedtuple('x', paramDict.keys())(*paramDict.values())))

print(repr(tstInstance))

Running the code above prints following representation of the object on the std output:

Test class data: name='Name Property Value', description='Description Property Value', number=102.0036

No comments:

Post a Comment