python munch库的使用解析


Posted in Python onMay 25, 2021

字典是 Python 中基础的数据结构之一,字典的使用,可以说是非常的简单粗暴,但即便是这样一个与世无争的数据结构,仍然有很多人 "看不惯它" 。
也许你并不觉得,但我相信,你看了这篇文章后,一定会和我一样,对原生字典开始有了偏见。
我举个简单的例子吧
当你想访问字典中的某个 key 时,你需要使用字典特定的访问方式,而这种方式需要你键入 一对中括号 还有 一对引号

>>> profile = dict(name="iswbm")
>>> profile
{'name': 'iswbm'}
>>> profile["name"]
'iswbm'

是不是开始觉得忍无可忍了?
如果可以像调用对象属性一样使用 . 去访问 key 就好了,可以省去很多多余的键盘击入,就像这样子

>>> profile.name
'iswbm'

是的,今天这篇文章就是跟大家分享一种可以直接使用 . 访问和操作字典的一个黑魔法库 -- 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.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

以上就是关于 munch 的使用全解,替换原生字典绝无问题,munch 的进一步封装使得数据的访问及操作更得更加 Pythonic 了,希望有一天这个特性能够体现在原生的字典上。

到此这篇关于python munch库的使用解析的文章就介绍到这了,更多相关python munch库的使用内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python ElementTree 基本读操作示例
Apr 09 Python
使用python将mdb数据库文件导入postgresql数据库示例
Feb 17 Python
python实现类似ftp传输文件的网络程序示例
Apr 08 Python
python实现逆波兰计算表达式实例详解
May 06 Python
Python功能键的读取方法
May 28 Python
对Python实现累加函数的方法详解
Jan 23 Python
详解Django-restframework 之频率源码分析
Feb 27 Python
使用pth文件添加Python环境变量方式
May 26 Python
Python实现迪杰斯特拉算法过程解析
Sep 18 Python
python实现发送QQ邮件(可加附件)
Dec 23 Python
Selenium Webdriver元素定位的八种常用方式(小结)
Jan 13 Python
python如何利用cv2.rectangle()绘制矩形框
Dec 24 Python
python调试工具Birdseye的使用教程
浅谈Python numpy创建空数组的问题
May 25 #Python
python实现语音常用度量方法的代码详解
python基础学习之生成器与文件系统知识总结
May 25 #Python
Python实战之实现简易的学生选课系统
May 25 #Python
python 如何用terminal输入参数
May 25 #Python
python 命令行传参方法总结
May 25 #Python
You might like
PHP设计模式之观察者模式(Observer)详细介绍和代码实例
2014/04/08 PHP
Zend Framework 2.0事件管理器(The EventManager)入门教程
2014/08/11 PHP
ThinkPHP中pathinfo的访问模式、路径访问模式及URL重写总结
2014/08/23 PHP
摘自织梦CMS的HTTP文件下载类
2015/08/08 PHP
Thinkphp 空操作、空控制器、命名空间(详解)
2017/05/05 PHP
ThinkPHP3.2.3框架实现执行原生SQL语句的方法示例
2019/04/03 PHP
PHP实用小技巧之调用录像的方法
2019/12/05 PHP
jQuery插件jQuery-JSONP开发ajax调用使用注意事项
2013/11/22 Javascript
JavaScript中的6种运算符总结
2014/10/16 Javascript
如何防止JavaScript自动插入分号
2015/11/05 Javascript
js提交form表单,并传递参数的实现方法
2016/05/25 Javascript
JavaScript 继承详解(六)
2016/10/11 Javascript
Angular5.1新功能分享
2017/12/21 Javascript
axios拦截设置和错误处理方法
2018/03/05 Javascript
jquery实现动态添加附件功能
2018/10/23 jQuery
浅谈Javascript中的对象和继承
2019/04/19 Javascript
vue使用recorder.js实现录音功能
2019/11/22 Javascript
vue中组件通信详解(父子组件, 爷孙组件, 兄弟组件)
2020/07/27 Javascript
在vue中实现给每个页面顶部设置title
2020/07/29 Javascript
[48:29]2018DOTA2亚洲邀请赛3月30日 小组赛A组 LGD VS KG
2018/03/31 DOTA
python使用PyGame播放Midi和Mp3文件的方法
2015/04/24 Python
Linux上安装Python的PIL和Pillow库处理图片的实例教程
2016/06/23 Python
python中 chr unichr ord函数的实例详解
2017/08/06 Python
python的中异常处理机制
2018/08/30 Python
Python实现简易过滤删除数字的方法小结
2019/01/09 Python
PyQt5实现类似别踩白块游戏
2019/01/24 Python
python读取word 中指定位置的表格及表格数据
2019/10/23 Python
python银行系统实现源码
2019/10/25 Python
k-means 聚类算法与Python实现代码
2020/06/01 Python
Python Django搭建网站流程图解
2020/06/13 Python
python如何实时获取tcpdump输出
2020/09/16 Python
h5页面背景图很长要有滚动条滑动效果的实现
2021/01/27 HTML / CSS
2014村务公开实施方案
2014/02/25 职场文书
2014年无财产无子女离婚协议书范本
2014/10/09 职场文书
2014年外联部工作总结
2014/11/17 职场文书
外贸英文求职信范文
2015/03/19 职场文书