本篇,我们讲一些有关 dict 的冷门操作,例如使用字典进行运算,或者一些特殊的、自带约束的字典。

字典可以用双星号 ** 进行解构,我们在番外篇4已经讲过了,大家自行取食:
(link)
这里讲的合并是 Python 3.9+ 版本后,新添加的内容。不同于前面讲到的用函数或者循环的方式,而是借助逻辑运算符 |(或)完成:
d1 = {"a": 1, "b": 2}d2 = {"b": 3, "c": 4}print(d1 | d2)# Output: {'a': 1, 'b': 3, 'c': 4}同样的,当键重复时,后面的字典中的内容会覆盖前面已有的内容。
给定两个字典,如何提取出他们 keys 中相同的部分:
此时,就可以使用逻辑运算符 &(与)完成:
d1 = {"a": 1, "b": 2}d2 = {"b": 3, "c": 4}res = d1.keys() & d2.keys()print(res, type(res))# Output: {'b'} <class 'set'>💡 注意:计算结果以 set(集合)的形式返回,如需进行其他操作,需要先进行类型转换。
OrderedDict 的作用是确保字典的内容按照插入顺序存储,而不是混乱排列:
from collections import OrderedDictod = OrderedDict()od["name"] = "RainBomb"od["age"] = 18print(dict(od))# Output: {'name': 'RainBomb', 'age': 18}其在使用上可以利用的特性是其对插入顺序的严格要求,即当两个字典的内容一样,但排列顺序不同时,就会判断两个字典不相等:
from collections import OrderedDictd1, d2 = {}, {}d1["name"] = "RainBomb"d1["age"] = 18d2["age"] = 18d2["name"] = "RainBomb"print(d1)print(d2)# Output: {'name': 'RainBomb', 'age': 18}# Output: {'age': 18, 'name': 'RainBomb'}od1 = OrderedDict(d1)od2 = OrderedDict(d2)print(od1)print(od2)# Output: OrderedDict({'name': 'RainBomb', 'age': 18})# Output: OrderedDict({'age': 18, 'name': 'RainBomb'})print(d1 == d2)# Output: Trueprint(od1 == od2)# Output: False对于一些特殊场景,我们创建了字典后,不想在后面的计算中将里面的内容进行修改,于是我们就要对字典添加只读保护,让字典只能被读取里面的数据,不能被修改:
from types import MappingProxyTyped = {"name": "RainBomb", "age": 18}read_d = MappingProxyType(d)print(read_d)# Output: {'name': 'RainBomb', 'age': 18}read_d["age"] = 20# Output: TypeError: 'mappingproxy' object does not support item assignment往期回顾:
介绍一下OpenCV-contrib这个库吧 | Part.12