字典是 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 , line 1, in
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以上就是关于 munch 的使用全解,替换原生字典绝无问题,munch 的进一步封装使得数据的访问及操作更得更加 pythonic 了,希望有一天这个特性能够体现在原生的字典上。
关于Microchip CEC1x02开发板分析介绍
新型柔性CIGS太阳能电池转换效率达23%,床下最新世界纪录
直流电机调速器电枢电压的设置
MiP切入Micro LED的竞争力有什么变化?
Excelitas公司推出µPAX-3脉冲氙气光源
关于替换原生字典munch的使用全解
中国联通完成基于AI的天线权值智能优化方案的测试
南亚科自研10nm DRAM DRAM产品可持续微缩至少三个时代
三星为什么要彻底关闭其在中国的手机工厂
数字资产交易平台HiEX介绍
音圈电机柔性振动供料系统的工作原理说明
制作激光恒流驱动电路
长光华芯完成B轮1.5亿融资,战略布局已全部完成
关于CCD与CMOS的区别分析
瑞萨e2studio(4)----使用J-Link烧写程序到瑞萨芯片
手机直连卫星火了,下一代互联网激烈竞争拉开帷幕
餐具表面洁净度快速检测仪的应用及特性说明
压电位移台简介!
数字滤波器的设计实验
华为聘请巴西前总统为顾问,以确保其在当地的5G地位