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.
python3
# 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) |
1 2 E 3 4
Time complexity: O(n), where n is the total number of elements in the input dictionary.
Auxiliary space: O(n), where n is the total number of elements in the input dictionary
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.
Python3
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) |
1 2 E 3 4