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.
python3
import json
class obj:
def __init__( self , dict1):
self .__dict__.update(dict1)
def dict2obj(dict1):
return json.loads(json.dumps(dict1), object_hook = obj)
dictionary = { 'A' : 1 , 'B' : { 'C' : 2 },
'D' : [ 'E' , { 'F' : 3 }], 'G' : 4 }
obj1 = dict2obj(dictionary)
print (obj1.A)
print (obj1.B.C)
print (obj1.D[ 0 ])
print (obj1.D[ 1 ].F)
print (obj1.G)
|
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):
if isinstance (d, list ):
d = [dict2obj(x) for x in d]
if not isinstance (d, dict ):
return d
class C:
pass
obj = C()
for k in d:
obj.__dict__[k] = dict2obj(d[k])
return obj
dictionary = { 'A' : 1 , 'B' : { 'C' : 2 },
'D' : [ 'E' , { 'F' : 3 }], 'G' : 4 }
obj2 = dict2obj(dictionary)
print (obj2.A)
print (obj2.B.C)
print (obj2.D[ 0 ])
print (obj2.D[ 1 ].F)
print (obj2.G)
|
Last Updated :
28 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...