Skip to content

Instantly share code, notes, and snippets.

@alphakilo7
Created January 12, 2021 05:31
Show Gist options
  • Save alphakilo7/2786550f801a74f781cd0ba6420c2a25 to your computer and use it in GitHub Desktop.
Save alphakilo7/2786550f801a74f781cd0ba6420c2a25 to your computer and use it in GitHub Desktop.
A class to convert a nested dictionary's keys into object based attributes.
class dict2obj:
"""
:class: dict2obj
---
:description: A class to convert a nested dictionary's keys into object based attributes.
---
:params:
- data_dict:dict - A standard python dictionary to convert into object.
"""
def __init__(self, data_dict):
self.__dict = data_dict
for k, v in data_dict.items():
if isinstance(v, (list, tuple)):
setattr(self, k, [dict2obj(it) if isinstance(it, dict) else it for it in v])
else:
setattr(self, k, dict2obj(v) if isinstance(v, dict) else v)
def __str__(self):
return dumps(self.__dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment