新西兰服务器

如何在python中使用munch库


如何在python中使用munch库

发布时间:2021-05-25 18:21:57 来源:高防服务器网 阅读:118 作者:Leah 栏目:开发技术

这篇文章给大家介绍如何在python中使用munch库,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1. 安装方法

使用如下命令进行安装

$ python -m pip install munch

2. 简单示例

munch 有一个 Munch 类,它继承自原生字典,使用 isinstance 可以验证

>>> from munch import Munch  >>> profile = Munch()  >>> isinstance(profile, dict)  True  >>>

并实现了点式赋值与访问,profile.name 与 profile['name'] 是等价的

>>> profile.name = "iswbm"  >>> profile.age = 18  >>> profile  Munch({'name': 'iswbm', 'age': 18})  >>>  >>> profile.name  'iswbm'  >>> profile["name"]  'iswbm'

3. 兼容字典的所有操作

本身 Munch 继承自 dict,dict 的操作也同样适用于 Munch 对象,不妨再来验证下
首先是:增删改查

# 新增元素  >>> profile["gender"] = "male"  >>> profile  Munch({'name': 'iswbm', 'age': 18, 'gender': 'male'})    # 修改元素  >>> profile["gender"] = "female"  >>> profile  Munch({'name': 'iswbm', 'age': 18, 'gender': 'female'})    # 删除元素  >>> profile.pop("gender")  'female'  >>> profile  Munch({'name': 'iswbm', 'age': 18})  >>>  >>> del profile["age"]  >>> profile  Munch({'name': 'iswbm'})

再者是:一些常用方法

>>> profile.keys()  dict_keys(['name'])  >>>  >>> profile.values()  dict_values(['iswbm'])  >>>  >>> profile.get('name')  'iswbm'  >>> profile.setdefault('gender', 'male')  'male'  >>> profile  Munch({'name': 'iswbm', 'gender': 'male'})

4. 设置返回默认值

当访问一个字典中不存在的 key 时,会报 KeyError 的错误

>>> profile = {}  >>> profile["name"]  Traceback (most recent call last):    File "<stdin>", line 1, in <module>  KeyError: 'name'

对于这种情况,通常我们会使用 get 来规避

>>> profile = {}  >>> profile.get("name", "undefined")  'undefined'

当然你在 munch 中仍然可以这么用,不过还有一种更好的方法:使用 DefaultMunch,它会在你访问不存在的 key 时,给你返回一个设定好的默认值

>>> from munch import DefaultMunch  >>> profile = DefaultMunch("undefined", {"name": "iswbm"})  >>> profile  DefaultMunch('undefined', {'name': 'iswbm'})  >>> profile.age  'undefined'  >>> profile  DefaultMunch('undefined', {'name': 'iswbm'})

5. 工厂函数自动创建key

上面使用 DefaultMunch 仅当你访问不存在的 key 是返回一个默认值,但这个行为并不会修改原 munch 对象的任何内容。
若你想访问不存在的 key 时,自动触发给原 munch 中新增你想要访问的 key ,并为其设置一个默认值,可以试一下 DefaultFactoryMunch 传入一个工厂函数。

>>> from munch import DefaultFactoryMunch  >>> profile = DefaultFactoryMunch(list, name='iswbm')  >>> profile  DefaultFactoryMunch(list, {'name': 'iswbm'})  >>>  >>> profile.brothers  []  >>> profile  DefaultFactoryMunch(list, {'name': 'iswbm', 'brothers': []})

6. 序列化的支持

Munch 支持序列化为 JSON 或者 YAML 格式的字符串对象
转换成 JSON

>>> from munch import Munch  >>> munch_obj = Munch(foo=Munch(lol=True), bar=100, msg='hello')  >>>  >>> import json  >>> json.dumps(munch_obj)  '{"foo": {"lol": true}, "bar": 100, "msg": "hello"}'

转换成 YAML

>>> from munch import Munch  >>> munch_obj = Munch(foo=Munch(lol=True), bar=100, msg='hello')  >>> import yaml  >>> yaml.dump(munch_obj)  '!munch.Munchnbar: 100nfoo: !munch.Munchn  lol: truenmsg: hellon'  >>>  >>> print(yaml.dump(munch_obj))  !munch.Munch  bar: 100  foo: !munch.Munch    lol: true  msg: hello    >>>

建议使用 safe_dump 去掉 !munch.Munch

>>> print(yaml.safe_dump(munch_obj))  bar: 100  foo:    lol: true  msg: hello

python主要应用领域有哪些

1、云计算,典型应用OpenStack。2、WEB前端开发,众多大型网站均为Python开发。3.人工智能应用,基于大数据分析和深度学习而发展出来的人工智能本质上已经无法离开python。4、系统运维工程项目,自动化运维的标配就是python+Django/flask。5、金融理财分析,量化交易,金融分析。6、大数据分析。

关于如何在python中使用munch库就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[