将嵌套的Python字典转换为对象
让我们看看如何将给定的嵌套字典转换为对象
方法一:使用json
模块。我们可以通过导入 json 模块并在json.loads()
方法中使用自定义对象挂钩来解决这个特殊问题。
# 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
方法 2:使用isinstance()
方法
.我们可以通过使用isinstance()
方法来解决这个特定问题,该方法用于检查对象是否是特定类的实例。
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