attrdict是第三方库,它提供的映射对象允许 它们的元素可以作为键和属性访问,需要安装。
pip install attrdict
示例代码1:
from attrdict import AttrDict
dic = {"name": "dgw", "age": 26}
ret = AttrDict(dic)
print(ret)
print()
print(ret.age)
运行结果:
示例代码2:
from attrdict import AttrDict
dic = {"name": "dgw", "age": 26, "info": {"province": "山东省", "city": "青岛市"}}
ret = AttrDict(dic)
print(ret)
print()
print()
print(.province)
print(.city)
print(ret("info").city)
运行结果:
示例代码3:
from attrdict import AttrDict
dic = {"name": "dgw", "age": 26, "info": {"province": "山东省", "city": "青岛市"},
"teachers": [{"name": "张老师"}, {"name": "李老师"}]}
ret = AttrDict(dic)
print(ret)
print()
print()
print(.province)
print(.city)
print(ret.teachers)
for a in ret.teachers:
print(a, type(a), )
运行结果:
默认情况下,相关的序列类型不是字节、str或unicode (例如,列表、元组)将自动转换为元组,其中 转换为属性的映射。