Convert a nested dictionary to an Object in Python

avatar

Borislav Hadzhiev

Last updated: Sep 16, 2022

banner

Photo from Unsplash

Convert a nested dictionary to an Object in Python #

To convert a nested dictionary to an object:

  1. Iterate over the dictionary's items in the __init__ method of a class.
  2. If the key has a value of type dict, instantiate the class with the value.
  3. Otherwise, set the key to the value.
main.py
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).

main.py
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.

main.py
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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.