Convert nested Python dictionary to object

Let us see how to convert a given nested dictionary into an object

Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json.loads() method.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the module
import json
   
# declaringa a class
class obj:
      
    # constructor
    def __init__(self, dict1):
        self.__dict__.update(dict1)
   
def dict2obj(dict1):
      
    # using json.loads method and passing json.dumps
    # method and custom object hook as arguments
    return json.loads(json.dumps(dict1), object_hook=obj)
     
# initializing the dictionary  
dictionary = {'A': 1, 'B': {'C': 2},
              'D': ['E', {'F': 3}],'G':4}
   
# calling the function dict2obj and
# passing the dictionary as argument
obj1 = dict2obj(dictionary)
   
# accessing the dictionary as an object
print (obj1.A)
print(obj1.B.C)
print(obj1.D[0])
print(obj1.D[1].F)
print(obj1.G)

chevron_right


Output

1
2
E
3
4

Method 2 : Using the isinstance() method

. We can solve this particular problem by using the isinstance() method which is used to check whether an object is an instance of a particular class or not.

filter_none

edit
close

play_arrow

link
brightness_4
code

def dict2obj(d):
      
    # checking whether object d is a
    # instance of class list
    if isinstance(d, list):
           d = [dict2obj(x) for x in d] 
  
    # if d is not a instance of dict then
    # directly object is returned
    if not isinstance(d, dict):
           return d
   
    # declaring a class
    class C:
        pass
   
    # constructor of the class passed to obj
    obj = C()
   
    for k in d:
        obj.__dict__[k] = dict2obj(d[k])
   
    return obj
  
# initializing the dictionary  
dictionary = {'A': 1, 'B': {'C': 2},
              'D': ['E', {'F': 3}],'G':4}
  
# calling the function dict2obj and
# passing the dictionary as argument 
obj2 = dict2obj(dictionary)
  
# accessing the dictionary as an object 
print(obj2.A)
print(obj2.B.C)
print(obj2.D[0])
print(obj2.D[1].F)
print(obj2.G)

chevron_right


Output

1
2
E
3
4



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.