(1)对于类似如下结构类型的数据,在一定的场合下,希望类似于info.student, info.student.name, info.teacher.course.math 等递归地通过点(.)的方式调用字典的数据
info={
"student":{
"name":"zhangsan",
"age":20,
"male":"man"
},
"teacher":{
"name":"Mr Wang",
"age":25,
"male":"woman",
"course":{
"math":"Friday",
"english":"Monday"
}
}
}
(2)可通过自定义如下类,然后将上述字典类型的数据转换一下即可
本质是递归的将字典类型的数据转换为Dotdict类型的(即实现了__getattr__的类)
class DotDict(dict):
def __init__(self, *args, **kwargs):
super(DotDict, self).__init__(*args, **kwargs)
def __getattr__(self, key):
value = self[key]
if isinstance(value, dict):
value = DotDict(value)
return value
(3)完整代码如下:
class DotDict(dict):
def __init__(self, *args, **kwargs):
super(DotDict, self).__init__(*args, **kwargs)
def __getattr__(self, key):
value = self[key]
if isinstance(value, dict):
value = DotDict(value)
return value
info={
"student":{
"name":"zhangsan",
"age":20,
"male":"man"
},
"teacher":{
"name":"Mr Wang",
"age":25,
"male":"woman",
"course":{
"math":"Friday",
"english":"Monday"
}
}
}
dot_info=DotDict(info)
print(dot_info.student)
print(dot_info.student.name)
print(dot_info.teacher.name)
print(dot_info.teacher.course.math)
执行结果如下:
{'name': 'zhangsan', 'age': 20, 'male': 'man'}
zhangsan
Mr Wang
Friday