终结 Python 原生字典?这个库要逆天改命了
Python技术
共 4782字,需浏览 10分钟
·
2021-06-19 22:11
>>> profile = dict(name="iswbm")
>>> profile
{'name': 'iswbm'}
>>> profile["name"]
'iswbm'
.
去访问 key 就好了,可以省去很多多余的键盘击入,就像这样子>>> profile.name
'iswbm'
.
访问和操作字典的一个黑魔法库 -- munch
。1. 安装方法
$ python -m pip install munch
2. 简单示例
>>> 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. 兼容字典的所有操作
# 新增元素
>>> 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. 设置返回默认值
>>> profile = {}
>>> profile["name"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'name'
>>> profile = {}
>>> profile.get("name", "undefined")
'undefined'
>>> 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 对象的任何内容。DefaultFactoryMunch
传入一个工厂函数。>>> from munch import DefaultFactoryMunch
>>> profile = DefaultFactoryMunch(list, name='iswbm')
>>> profile
DefaultFactoryMunch(list, {'name': 'iswbm'})
>>>
>>> profile.brothers
[]
>>> profile
DefaultFactoryMunch(list, {'name': 'iswbm', 'brothers': []})
6. 序列化的支持
>>> 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"}'
>>> 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
PS:公号内回复「Python」即可进入Python 新手学习交流群,一起 100 天计划!
老规矩,兄弟们还记得么,右下角的 “在看” 点一下,如果感觉文章内容不错的话,记得分享朋友圈让更多的人知道!
![](https://filescdn.proginn.com/cceef726fe791f1a3e1d56e818d8c743/ff667c35f4048f5f72ae36b346096cf6.webp)
![](https://filescdn.proginn.com/e466a6973780a38e3aa91b75180910fb/c7e0ad55540c996c4724876fa0d174f0.webp)
【代码获取方式】
评论