Python Dictionary to Python Object Converter For Beginners

A Class in python to convert a dictionary to an object

Run the Script:

  • Add the class obj in your code.
  • Modify the code according to your need or use it directly: ob = obj({'a':1, 'b': 2, 'c':3})

Source Code:

conversion.py

class obj(object):
    def __init__(self, d):
        for x, y in d.items():
            setattr(self, x, obj(y) if isinstance(y, dict) else y)
data = {'a':5,'b':7,'c':{'d':8}}
ob = obj(data)

Leave a Comment