关于python:终结-Python-原生字典这个库要逆天改命了

8次阅读

共计 2943 个字符,预计需要花费 8 分钟才能阅读完成。

字典是 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 了,心愿有一天这个个性可能体现在原生的字典上。

最近整顿了几百 G 的 Python 学习材料,蕴含新手入门电子书、教程、源码等等,收费分享给大家!想要的返回“Python 编程学习圈”,发送“J”即可收费取得

正文完
 0