python munch库的使用解析

字典是 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库的使用内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python中必会的四大高级数据类型(字符,元组,列表,字典)

    一. 字符串 生活中我们经常坐大巴车,每个座位一个编号,一个位置对应一个下标. 字符串中也有下标,要取出字符串中的部分数据,可以用下标取. python中使用切片来截取字符串其中的一段内容,切片截取的内容不包含结束下标对应的数据. 切片使用语法:[起始下标:结束下标:步长] ,步长指的是隔几个下标获取一个字符. 注意:下标会越界,切片不会 常用函数 练习: Test='rodma ' print(type(Test)) print('Test的一个字符串%s'%Test[0])#跟数组差不多 #

  • python字典按照value排序方法

    python中,我们可以对列表.字符串.元祖中的元素进行排序,那对于字典中的元素可以排序吗?其实对于字典本身我们无法进行排序,但是我们可以对字典按值排序.本文介绍python中对字典按照value进行排序的三种方法. 方法一:key使用lambda匿名函数取value进行排序 dict= {'a':1,'b':4,'c':2} sorted(dict.items(),key = lambda x:x[1],reverse = True) 方法二:使用operator的itemgetter进行排序

  • Python字典实现伪切片功能

    故事是从这里开始的- 早上起床看到一条评论,有点懵逼,字典切片? 查阅了一下Python资料,3.6版本的Python改写了dict的内部算法,3.6版本之前是无序的; So,现在就是有序的啦,注意的是这个顺序是key的插入顺序; 但字典虽有序没下标怎么切片?list列表? 那就把key放进list里,利用list自身的截取方法切一下片! 再用截取后的key对新的字典赋值! 所以脑子一热就写了个字典切片1.0版本 # 字典切片1.0版本 def dictcut(dict, start, end)

  • Python txt文件如何转换成字典

    处理前文件内容 代码 处理后的 # 读取代码 fr = open('three.txt', 'r') dic = {} keys = [] # 用来存储读取的顺序 for line in fr: v = line.strip().split(':') dic[v[0]] = v[1] keys.append(v[0]) fr.close() print(dic) # # 写入文件代码 通过keys的顺序写入 # fw = open('wdic.txt', 'w') # for k in keys

  • python 获取字典键值对的实现

    获 得 字 典 键. 值 的 函 数 有: items/ iteritems/ keys/ iterkeys/ values/ itervalues 通 过 以 上 这 些 函 数 得 到 的 是 键 或 者 值 的 列 表. 例: a_dict = {" name": "sir", "lang": "python", "email": "sir@ gmail.com", "w

  • python字典与json转换的方法总结

    在python中json分别由列表和字典组成,本文主要介绍python中字典与json相互转换的方法.使用json.dumps可以把字典转成json字符串.使用json.loads可以把json字符串转为字典类型的数据. 1.字典转json 使用json.dumps json.dumps是对python对象编码成json对象,可以把字典转成json字符串. 方法格式 #字典转换成json字符串 json.dumps(dict) 实例 # 创建字典 info_dict = {'name': 'Jo

  • python3访问字典里的值实例方法

    如今,字典也是我们在学习python时候的一个热门话题,很多人都说,只要掌握了字典,就相当于掌握了python的半壁江山,事实上,为什么大家都会这么说呢?通常我们使用字典时候,总会遇到编程数据里的三部曲,编写.访问.使用,而其中访问也算是一个比较重要的内容了,一起来看下吧~ 访问值 我们通过提供索引来访问列表中的值.类似地,在字典中,通过使用键来访问值. grades['John'] 'A' grades.get('Betty') 'B' 访问所有值或所有键 keys方法用于获取所有键. gra

  • 在Python中字典按值排序的实现方法

    一.sorted高阶函数 这种方法更为简洁,更为推荐. d={'a':1,'c':3,'b':2} # 首先建一个字典d #d.items()返回的是: dict_items([('a', 1), ('c', 3), ('b', 2)]) d_order=sorted(d.items(),key=lambda x:x[1],reverse=False) # 按字典集合中,每一个元组的第二个元素排列. # x相当于字典集合中遍历出来的一个元组. print(d_order) # 得到: [('a'

  • 浅谈Python列表嵌套字典转化的问题

    在看视频教程的时候提到了[{'a' : 97}, {'b' : 98}, {'c' : 99}, {'d' : 100}, {'e' : 101}, ...........]形式的列表嵌套形式, 要求是将上述列表转换为{'a' : 97,'b' : 98,'c' : 99 ,'d' : 100,'e' : 101,.....}的字典形式 首先上述的a--->97, b--->98,.....意思是key为a到z的英文小写字母,value值为对应的ascii码, 那么一开始可以结合range()

  • Python 如何读取字典的所有键-值对

    如果字典中存储了一些值,我想要取出来该怎么操作呢? 1.我要取出字典中所有的键-值对 取出字典中所有的键-值对时,可以使用items()返回一个键值对列表,并配合for循环进行遍历 #创建一个存储一个学生的信息,通过遍历可以取出所有信息 student={'name':'xiaoming','age':11,'school':'tsinghua'} for key,value in student.items(): print(key+':'+str(value)) 输出: age:11 nam

随机推荐