attrdict是第三方库,它提供的映射对象允许 它们的元素可以作为键和属性访问,需要安装。
pip install attrdict
示例代码1:
from attrdict import AttrDict
dic = {"name": "dgw", "age": 26}
ret = AttrDict(dic)
print(ret)
print(ret.name)
print(ret.age)
运行结果:
示例代码2:
from attrdict import AttrDict
dic = {"name": "dgw", "age": 26, "info": {"province": "山东省", "city": "青岛市"}}
ret = AttrDict(dic)
print(ret)
print(ret.name)
print(ret.info)
print(ret.info.province)
print(ret.info.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(ret.name)
print(ret.info)
print(ret.info.province)
print(ret.info.city)
print(ret.teachers)
for a in ret.teachers:
print(a, type(a), a.name)
运行结果:
默认情况下,相关的序列类型不是字节、str或unicode (例如,列表、元组)将自动转换为元组,其中 转换为属性的映射。
参考博文:
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142809.html