Convert a nested dictionary to an Object in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
2 min

banner

# 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

convert nested dictionary to object

The code for this article is available on GitHub

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]
The code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev