字典
关键代码:
class Mapping(Collection):
def get(self, key, default=None):
try:
return self[key]
except KeyError:
return default
def __contains__(self, key):
try:
self[key]
except KeyError:
return False
else:
return True
def keys(self):
return KeysView(self)
def items(self):
return ItemsView(self)
def values(self):
return ValuesView(self)
def __eq__(self, other):
if not isinstance(other, Mapping):
return NotImplemented
return dict(self.items()) == dict(other.items())
字典变种:
- OrderedDict保持添加顺序
- ChainMap 多个map依次链接,越靠前优先级越高
- Counter 多重集合或计数器
- UserDict 用于被继承的dict
- MappingProxyType 创建一个只读视图(>=3.3)