# 通过LookupDict构建个可以根据多个value查找key的字典
class LookupDict(dict):
"""Dictionary lookup object."""
def __init__(self, name=None):
self.name = name
super(LookupDict, self).__init__()
def __repr__(self):
return '<lookup \'%s\'>' % (self.name)
def __getitem__(self, key):
# We allow fall-through here, so values default to None
return self.__dict__.get(key, None)
def get(self, key, default=None):
return self.__dict__.get(key, default)
In [2]: _codes = {
...:
...: # Informational.
...: 100: ('continue',),
...: 101: ('switching_protocols',),
...: 102: ('processing',),
...: 103: ('checkpoint',),
...: 122: ('uri_too_long', 'request_uri_too_long')
...: }
In [3]: codes = LookupDict(name='status_codes')
In [4]: for code, titles in _codes.items():
...: for title in titles:
...: setattr(codes, title, code)
...: if not title.startswith('\\'):
...: setattr(codes, title.upper(), code)
...:
In [5]: codes
Out[5]: <lookup 'status_codes'>
In [6]: codes.processing
Out[6]: 102
In [7]: codes.checkpoint
Out[7]: 103
# codes的__dict__如下
In [8]: codes.__dict__
Out[8]:
{'CHECKPOINT': 103,
'CONTINUE': 100,
'PROCESSING': 102,
'REQUEST_URI_TOO_LONG': 122,
'SWITCHING_PROTOCOLS': 101,
'URI_TOO_LONG': 122,
'checkpoint': 103,
'continue': 100,
'name': 'status_codes',
'processing': 102,
'request_uri_too_long': 122,
'switching_protocols': 101,
'uri_too_long': 122}
# CaseInsensitiveDict定义了大小不敏感的字典
class CaseInsensitiveDict(collections.MutableMapping):
"""
cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json' # True
list(cid) == ['Accept'] # True"""
def __init__(self, data=None, **kwargs):
self._store = OrderedDict()
if data is None:
data = {}
self.update(data, **kwargs)
def __setitem__(self, key, value):
# Use the lowercased key for lookups, but store the actual
# key alongside the value.
self._store[key.lower()] = (key, value)
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
def __len__(self):
return len(self._store)
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
)
def __eq__(self, other):
if isinstance(other, collections.Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
# Compare insensitively
return dict(self.lower_items()) == dict(other.lower_items())
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
return str(dict(self.items()))
MutableMapping的定义是实现__getitem__,__setitem__,__delitem__,__iter__,__len__方法的对象。
CaseInsensitiveDict通过将key转换为小写进行查找,在字典值中以元组的形式存储了原始键和值。
lower_items()返回小写的key,和原始的value。
In [13]: cid = CaseInsensitiveDict()
In [16]: cid
Out[16]: {'Accept': 'application/json'}
In [19]: cid.__dict__
Out[19]: {'_store': OrderedDict([('accept', ('aCCEPT', 'application/json'))])}
In [30]: list(cid.lower_items())
Out[30]: [('accept', 'application/json'), ('ab', 'Cd')]
In [31]: cid._store.items()
Out[31]: odict_items([('accept', ('aCCEPT', 'application/json')), ('ab', ('Ab', 'Cd'))])