Created
January 12, 2021 05:31
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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