python中munch库的作用是什么?怎样使用?
Admin 2021-08-24 群英技术资讯 2038 次浏览
python中munch库的作用是什么?怎样使用?如果对Python中字典熟悉的朋友,应该比较了解munch库,munch库能够直接使用 .,访问和操作字典,这要比原生字典的使用方便很多,下面我们就来具体了解看看munch库。
字典是 Python 中基础的数据结构之一,字典的使用,可以说是非常的简单粗暴,但即便是这样一个与世无争的数据结构,仍然有很多人 "看不惯它" 。
也许你并不觉得,但我相信,你看了这篇文章后,一定会和我一样,对原生字典开始有了偏见。
我举个简单的例子吧!当你想访问字典中的某个 key 时,你需要使用字典特定的访问方式,而这种方式需要你键入 一对中括号 还有 一对引号
>>> profile = dict(name="iswbm")
>>> profile
{'name': 'iswbm'}
>>> profile["name"]
'iswbm'
是不是开始觉得忍无可忍了?如果可以像调用对象属性一样使用 . 去访问 key 就好了,可以省去很多多余的键盘击入,就像这样子
>>> profile.name 'iswbm'
是的,今天这篇文章就是跟大家分享一种可以直接使用 . 访问和操作字典的一个黑魔法库 -- munch。
使用如下命令进行安装
$ python -m pip install munch
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'
本身 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'})
当访问一个字典中不存在的 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'})
上面使用 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': []})
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.Munch\nbar: 100\nfoo: !munch.Munch\n lol: true\nmsg: hello\n' >>> >>> 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的munch库的作用和用法的介绍,希望对大家学习和了解munch库有帮助,想要了解更多python的munch库的内容,请搜索群英网络以前的文章或继续浏览其他相关的文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了python3 实现mysql数据库连接池的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
默认情况下pytest测试用例的执行顺序是先按照外层后内层(目录下的文件),同层级的包或文件、根据名称、按照ascii码升序执行,文件内的用例根据先后顺序执行,这篇文章主要给大家介绍了关于pytest多文件执行顺序控制的相关资料,需要的朋友可以参考下
Radiobutton组件用于实现多选一的问题,本文主要介绍了Tkinter组件实现Radiobutton的示例,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
这篇文章给大家分享的是Django模板中两个变量运算的实现,文中示例代码介绍的非常详细,对大家学习和理解Django模板中的变量运算有一定的帮助,感兴趣的朋友接下来一起跟随小编看看吧。
今天很有可能你已经做了一些使用滑动窗口(也称为移动窗口)的事情,而你甚至不知道它。例如:许多编辑算法都是基于移动窗口的。在GIS中做地形分析的大多数地形栅格度量(坡度、坡向、山坡阴影等)都基于滑动窗口。很多情况下,对格式化为二维数组的数据进行分析时,都很有可能涉及到滑动窗口。滑动窗口操作非常普遍,非常有用。它们也很容易在Python中实现。学习如何实现移动窗口将把你的数据分析和争论技能提升到一个新的水平。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008