终结 Python 原生字典?这个库要逆天改命了

开发 后端
字典是 Python 中基础的数据结构之一,字典的使用,可以说是非常的简单粗暴,但即便是这样一个与世无争的数据结构,仍然有很多人 "看不惯它" 。

大家好,我是明哥,今天来聊一聊与字典相关的话题。

字典是 Python 中基础的数据结构之一,字典的使用,可以说是非常的简单粗暴,但即便是这样一个与世无争的数据结构,仍然有很多人 "看不惯它" 。

[[401175]]

也许你并不觉得,但我相信,你看了这篇文章后,一定会和我一样,对原生字典开始有了偏见。我举个简单的例子吧当你想访问字典中的某个 key 时,你需要使用字典特定的访问方式,而这种方式需要你键入 一对中括号 还有 一对引号

  1. >>> profile = dict(name="iswbm"
  2. >>> profile 
  3. {'name': 'iswbm'} 
  4. >>> profile["name"] 
  5. 'iswbm' 

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

  1. >>> profile.name 
  2. 'iswbm' 

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

1. 安装方法

使用如下命令进行安装

  1. $ python -m pip install munch 

2. 简单示例

munch 有一个 Munch 类,它继承自原生字典,使用 isinstance 可以验证

  1. >>> from munch import Munch 
  2. >>> profile = Munch() 
  3. >>> isinstance(profile, dict) 
  4. True 
  5. >>> 

并实现了点式赋值与访问,profile.name 与 profile['name'] 是等价的

  1. >>> profile.name = "iswbm" 
  2. >>> profile.age = 18 
  3. >>> profile 
  4. Munch({'name': 'iswbm', 'age': 18}) 
  5. >>> 
  6. >>> profile.name 
  7. 'iswbm' 
  8. >>> profile["name"] 
  9. 'iswbm' 

3. 兼容字典的所有操作

本身 Munch 继承自 dict,dict 的操作也同样适用于 Munch 对象,不妨再来验证下首先是:增删改查

  1. # 新增元素 
  2. >>> profile["gender"] = "male" 
  3. >>> profile 
  4. Munch({'name': 'iswbm', 'age': 18, 'gender': 'male'}) 
  5.  
  6. # 修改元素 
  7. >>> profile["gender"] = "female" 
  8. >>> profile 
  9. Munch({'name': 'iswbm', 'age': 18, 'gender': 'female'}) 
  10.  
  11. # 删除元素 
  12. >>> profile.pop("gender") 
  13. 'female' 
  14. >>> profile 
  15. Munch({'name': 'iswbm', 'age': 18}) 
  16. >>> 
  17. >>> del profile["age"] 
  18. >>> profile 
  19. Munch({'name': 'iswbm'}) 

再者是:一些常用方法

  1. >>> profile.keys() 
  2. dict_keys(['name']) 
  3. >>> 
  4. >>> profile.values() 
  5. dict_values(['iswbm']) 
  6. >>> 
  7. >>> profile.get('name') 
  8. 'iswbm' 
  9. >>> profile.setdefault('gender', 'male') 
  10. 'male' 
  11. >>> profile 
  12. Munch({'name': 'iswbm', 'gender': 'male'}) 

4. 设置返回默认值

当访问一个字典中不存在的 key 时,会报 KeyError 的错误

  1. >>> profile = {} 
  2. >>> profile["name"] 
  3. Traceback (most recent call last): 
  4.   File "<stdin>", line 1, in <module> 
  5. KeyError: 'name' 

对于这种情况,通常我们会使用 get 来规避

  1. >>> profile = {} 
  2. >>> profile.get("name", "undefined") 
  3. 'undefined' 

当然你在 munch 中仍然可以这么用,不过还有一种更好的方法:使用 DefaultMunch,它会在你访问不存在的 key 时,给你返回一个设定好的默认值

  1. >>> from munch import DefaultMunch 
  2. >>> profile = DefaultMunch("undefined", {"name": "iswbm"}) 
  3. >>> profile 
  4. DefaultMunch('undefined', {'name': 'iswbm'}) 
  5. >>> profile.age 
  6. 'undefined' 
  7. >>> profile 
  8. DefaultMunch('undefined', {'name': 'iswbm'}) 

5. 工厂函数自动创建key

上面使用 DefaultMunch 仅当你访问不存在的 key 是返回一个默认值,但这个行为并不会修改原 munch 对象的任何内容。若你想访问不存在的 key 时,自动触发给原 munch 中新增你想要访问的 key ,并为其设置一个默认值,可以试一下 DefaultFactoryMunch 传入一个工厂函数。

  1. >>> from munch import DefaultFactoryMunch 
  2. >>> profile = DefaultFactoryMunch(list, name='iswbm'
  3. >>> profile 
  4. DefaultFactoryMunch(list, {'name': 'iswbm'}) 
  5. >>> 
  6. >>> profile.brothers 
  7. [] 
  8. >>> profile 
  9. DefaultFactoryMunch(list, {'name': 'iswbm', 'brothers': []}) 

6. 序列化的支持

Munch 支持序列化为 JSON 或者 YAML 格式的字符串对象

转换成 JSON:

  1. >>> from munch import Munch 
  2. >>> munch_obj = Munch(foo=Munch(lol=True), bar=100msg='hello'
  3. >>> 
  4. >>> import json 
  5. >>> json.dumps(munch_obj) 
  6. '{"foo": {"lol": true}, "bar": 100, "msg": "hello"}' 

转换成 YAML:

  1. >>> from munch import Munch 
  2. >>> munch_obj = Munch(foo=Munch(lol=True), bar=100msg='hello'
  3. >>> import yaml 
  4. >>> yaml.dump(munch_obj) 
  5. '!munch.Munch\nbar: 100\nfoo: !munch.Munch\n  lol: true\nmsg: hello\n' 
  6. >>> 
  7. >>> print(yaml.dump(munch_obj)) 
  8. !munch.Munch 
  9. bar: 100 
  10. foo: !munch.Munch 
  11.   lol: true 
  12. msg: hello 
  13.  
  14. >>> 

建议使用 safe_dump 去掉 !munch.Munch:

  1. >>> print(yaml.safe_dump(munch_obj)) 
  2. bar: 100 
  3. foo: 
  4.   lol: true 
  5. msg: hello 

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

 

责任编辑:赵宁宁 来源: Python编程时光
相关推荐

2018-05-04 10:45:58

戴尔

2019-03-04 08:48:23

Spring WebFJavaIO

2022-08-31 15:57:11

程序员

2014-09-02 17:33:05

魅族黄章MX4

2021-07-06 07:21:16

Spring 安全平台

2023-09-26 07:22:20

2022-05-17 08:40:20

PythonWiFi密码代码

2018-01-16 08:40:13

SSD市场缺货

2017-02-17 16:43:15

人工智能AI技术Wear 2.0

2017-05-09 16:20:47

3D打印3D食品

2022-04-15 15:11:41

清华计算机研究所

2018-05-23 15:01:46

程序员WiFi生产商

2022-04-29 10:27:58

数据库删库MySQL

2019-10-31 15:13:11

Python

2013-01-09 10:02:06

U盘金士顿1TB容量

2019-05-15 10:55:07

机器学习数据库索引

2012-02-22 09:16:31

JavaJava SE 6

2017-02-10 18:13:46

谷歌大脑人工智能

2016-10-08 10:09:16

华为HDG开发者

2020-12-22 06:18:47

Windows 10Windows操作系统
点赞
收藏

51CTO技术栈公众号