Python的dict类型,一般称之为字典类型
key的顺序
python 3.6之前是插入无顺序的,python3.6之后插入有顺序的
**
删除
**
1,del dic[“k”] 移除字典中键为k的键值对,没有返回值。
若是k不存在,则报错“KeyError”
2,pop 删除键值对: dic.pop(k,[default]),
返回键k所对应的值,然后移除这个键值对
若是k不存在,则返回default值,若k不存在且没有设置default值,会引发“KeyError”错误
**
字典的比较
**
__eq__魔术方法的使用
有序字典 OrderDict
from collections import OrderedDict
OrderDict的__eq__实现如下
def __eq__(self, other):
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
while comparison to a regular mapping is order-insensitive.
'''
if isinstance(other, OrderedDict):
return dict.__eq__(self, other) and all(map(_eq, self, other))
return dict.__eq__(self, other)
解析:
有序字典的比较,一个是元素值的相等,还要依次取两个比较字典的元素比较(即值相同还要顺序一致)
普通字典的等值比较就是元素值的比较
print("=== Dict equal使用")
test_dict1={1:"qq"}
test_dict2={1:"qq"}
test_dict1[2]="ssss"
test_dict1[3]="ttt"
test_dict2[3]="ttt" #先加入key=3
test_dict2[2]="ssss"
print(test_dict1)
print(test_dict2)
print(test_dict1==test_dict2)
print("=== orderDict equal使用")
test_ordict1=OrderedDict({1:"qq"})
test_ordict2=OrderedDict({1:"qq"})
test_ordict1[2]="ssss"
test_ordict1[3]="ttt"
test_ordict2[3]="ttt" #先加入key=3
test_ordict2[2]="ssss"
print(test_ordict1)
print(test_ordict2)
print(test_ordict1==test_ordict2)
print("=== Dict与orderDict equal使用")
print(test_ordict1==test_dict1)
结果
=== Dict equal使用
{1: 'qq', 2: 'ssss', 3: 'ttt'}
{1: 'qq', 3: 'ttt', 2: 'ssss'}
True
=== orderDict equal使用
OrderedDict([(1, 'qq'), (2, 'ssss'), (3, 'ttt')])
OrderedDict([(1, 'qq'), (3, 'ttt'), (2, 'ssss')])
False
=== Dict与orderDict equal使用
True
两个字典的比较,归根到底还是值及顺序的比较,不涉及hash id的比较
**
__missing__魔术方法的使用
**
__missing__魔术方法是当key值不存在的时候调用的,但是 如果未定义 missing(),则会引发 KeyError
class dictClass(dict):
def __missing__(self, key):
print("missing key:",key)
#default dict就是无key值时候返回__missing__魔术方法
test_dict=dictClass({1:"sss",2:"jjj",3:"uuu"})
test_dict[9]
结果:
missing key: 9
l 操作
3.9 新版功能.
d | other
合并 d 和 other 中的键和值来创建一个新的字典,两者必须都是字典。当 d 和 other 有相同键时, other 的值优先。