Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Convert nested Python dictionary to object

  • Last Updated : 25 Aug, 2020

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




# 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)
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.




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)
Output
1
2
E
3
4



My Personal Notes arrow_drop_up
Recommended Articles
Page :