Python Dict to Object

Jul 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']

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.