Last updated: Apr 9, 2024
Reading timeยท2 min

To convert a nested dictionary to an object:
__init__ method of a class.dict, instantiate the class with the value.class Struct: def __init__(self, **kwargs): for key, value in kwargs.items(): if isinstance(value, dict): self.__dict__[key] = Struct(**value) else: self.__dict__[key] = value my_dict = { 'name': 'bobbyhadz', 'address': { 'country': 'Country A', 'city': 'City A', 'codes': [1, 2, 3] }, } obj = Struct(**my_dict) print(obj.address.country) # ๐๏ธ Country A print(obj.address.codes) # ๐๏ธ [1, 2, 3] print(obj.name) # ๐๏ธ bobbyhadz obj.address.greet = 'hello world' print(obj.address.greet) # ๐๏ธ hello world

The Struct class takes keyword arguments and uses the __dict__ attribute on
the object to convert the nested dictionary to an object.
The __dict__ attribute returns a dictionary containing the object's properties
and values.
We used the dict.items() method to iterate over the dictionary's items.
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.items()) # ๐๏ธ dict_items([('id', 1), ('name', 'BobbyHadz')])
On each iteration, we check if the current key points to a dictionary and if it
does, we recursively pass the dictionary to the Struct class.
class Struct: def __init__(self, **kwargs): for key, value in kwargs.items(): if isinstance(value, dict): self.__dict__[key] = Struct(**value) else: self.__dict__[key] = value my_dict = { 'name': 'bobbyhadz', 'address': { 'country': 'Country A', 'city': 'City A', 'codes': [1, 2, 3] }, } obj = Struct(**my_dict) print(obj.address.country) # ๐๏ธ Country A print(obj.address.codes) # ๐๏ธ [1, 2, 3]
If the key doesn't point to a nested dictionary, we add it to the __dict__
attribute.
You can access nested attributes on the object using dot notation.
If you try to access an attribute that is not present on the object, an
AttributeError is raised.
You can learn more about the related topics by checking out the following tutorials: