温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python黑魔法库安装及操作字典的方法教程

发布时间:2021-10-25 16:22:54 来源:亿速云 阅读:275 作者:iii 栏目:开发技术

本篇内容主要讲解“Python黑魔法库安装及操作字典的方法教程”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“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.nameprofile['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

>>> dict_obj = {"1.2": "hello"} >>> dict_obj["1.2"] 'hello'

7. 说说局限性

以上就是关于 munch 的使用全解,munch 的进一步封装使得数据的访问及操作更得更加 Pythonic ,替换原生字典在大部分场景下都不会有太大问题。

但同时也不得不承认,munch 在一些场景下无法达到原生字典的效果,比如我想字典里的 key 为 "1.2" 的时候,原生字典能很好的表示它。

>>> dict_obj = {"1.2": "hello"} >>> dict_obj["1.2"] 'hello'

切换到 munch ,你会发现无法在初始化 munch 对象的时候,传入 1.2 的 key

>>> from munch import Munch >>> dict_obj = Munch(1.2="hello")   File "<stdin>", line 1     dict_obj = Munch(1.2="hello")                      ^ SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

就算你用原生的字典的方式添加了这个 key-value,也根本无法使用 . 的方式取到 1.2 对应的 value。

>>> from munch import Munch >>> dict_obj = Munch() >>> dict_obj["1.2"]="hello" >>> dict_obj Munch({'1.2': 'hello'}) >>> dict_obj.1.2   File "<stdin>", line 1     dict_obj.1.2             ^ SyntaxError: invalid syntax

也正是因为这样,原生字典至今还是不可替代的存在。

以上就今天跟大家分享的内容,这篇文章是《Python黑魔法手册》 v3.0 版的最后一篇文章,目前 PDF 已经制作完成。

Python黑魔法库安装及操作字典的方法教程

到此,相信大家对“Python黑魔法库安装及操作字典的方法教程”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI