Python Dict to Object

July 13, 2019

The following code is by Nadia Alramli posted at StackOverflow

class to_obj(object):
    def __init__(self, d):
        for a, b in d.items():
            if isinstance(b, (list, tuple)):
               setattr(self, a, [to_obj(x) if isinstance(x, dict) else x for x in b])
            else:
               setattr(self, a, to_obj(b) if isinstance(b, dict) else b)

Usage

data = {
    'age': 40,
    'name': {
        'first': 'Desmond',
        'last': 'Lua'
    },
    'friends': ['Mei Ru', 'JackJack', 'Bob']
}

x = to_obj(data)
print(x.age)
print(x.name.first)
print(x.friends)

Output

40
Desmond
['Mei Ru', 'JackJack', 'Bob']
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.