about dict
6867 ワード
the method __missing__
defaultdictの内部で何が起こったの?これは辞書の内部の__からmissing__方法といえば.missing__からのみgetitem__メソッド呼び出し.いったん_getitem__keyが見つからなくて、この時_missing__呼び出されます.difaultdict_ではfactoryの_missing__メソッドではlist()を呼び出し,結果をd[key]に付与した.
search dict.keys()
A search like k in my_dict.keys() is efficient in Python 3 even for very large mappings because dict.keys() returns a view, which is similar to a set, and containment checks in sets are as fast as in dictionaries. Details are documented in the “Dictionary” view objects section of the documentation. In Python 2, dict.keys() returns a list, so our solution also works there, but it is not efficient for large dictionaries, because k in my_list must scan the list.
異なるdict
collections.OrderedDict
順序辞書、辞書は挿入の順序を覚えて、反復する時に先に挿入したことにアクセスして、最後に最後に挿入したことにアクセスします.The popitem method of an OrderedDict pops the first item by default, but if called as my_odict.popitem(last=True), it pops the last item added.
collections.ChainMap
キーを入力すると、chainmapは各mapの値を逐次検索し、存在して戻るまで検索します.key-valueを変更すると、最初のmapのkey-valueペアのみが変更されます.
collections.Counter
Counterは、反復可能なオブジェクト内の各要素の出現回数を統計しますが、各要素はhashableでなければなりません.
collections.UserDict
A pure Python implementation of a mapping that works like a standard dict.これは親として継承されて使用されます.これとdictの大きな違いは、UserDictが自分のデータを露出するselfを直接使うことである.Dataは直接アクセスできますdataは辞書です.たとえば、データのセットにintがあり、str(int)タイプがkeyとしてクエリーにアクセスするため、UserDictを使用して現在の環境で適切な辞書構造を作成できます.
継承関係StrDict->UserDict->MutableMapping->Mappingを見てみましょう
MutableMapping.update This powerful method can be called directly but is also used by __init__ to load the instance from other mappings, from iterables of (key, value) pairs, and keyword arguments. Because it uses self[key] = value to add items, it ends up calling our implementation of __setitem__. Mapping.get In StrKeyDict, we had to code our own get to obtain results consistent with __getitem__, but in Example 3-8 we inherited Mapping.get, which is implemented exactly like StrKeyDict0.get.
Immutable Mappings
The mapping types provided by the standard library are all mutable, but you may need to guarantee that a user cannot change a mapping by mistake. Since Python 3.3, the types module provides a wrapper class called MappingProxyType, which, given a mapping, returns a mappingproxy instance that is a read-only but dynamic view of the original mapping. This means that updates to the original mapping can be seen in the mappingproxy, but changes cannot be made through it.
>>>from collections import defaultdict
>>>d = defaultdict(list)
>>>d['a'].append(1)
>>>d['b'].append(2)
>>>d
defaultdict(<class 'list'>, {'b': [2], 'a': [1]})
>>>d.get('c',None)
>>>d['c']
[]
defaultdictの内部で何が起こったの?これは辞書の内部の__からmissing__方法といえば.missing__からのみgetitem__メソッド呼び出し.いったん_getitem__keyが見つからなくて、この時_missing__呼び出されます.difaultdict_ではfactoryの_missing__メソッドではlist()を呼び出し,結果をd[key]に付与した.
search dict.keys()
A search like k in my_dict.keys() is efficient in Python 3 even for very large mappings because dict.keys() returns a view, which is similar to a set, and containment checks in sets are as fast as in dictionaries. Details are documented in the “Dictionary” view objects section of the documentation. In Python 2, dict.keys() returns a list, so our solution also works there, but it is not efficient for large dictionaries, because k in my_list must scan the list.
異なるdict
collections.OrderedDict
順序辞書、辞書は挿入の順序を覚えて、反復する時に先に挿入したことにアクセスして、最後に最後に挿入したことにアクセスします.The popitem method of an OrderedDict pops the first item by default, but if called as my_odict.popitem(last=True), it pops the last item added.
collections.ChainMap
キーを入力すると、chainmapは各mapの値を逐次検索し、存在して戻るまで検索します.key-valueを変更すると、最初のmapのkey-valueペアのみが変更されます.
>>>import collections
>>>cmap = collections.ChainMap() # chainMap(): {}
>>>a = {'a':1}
>>>b = {'b':2}
>>>cmap.new_child(a) # map, ChainMap
ChainMap({'a': 1}, {})
>>>cmap # cmap
ChainMap({})
>>>cmap.update(a)
>>>cmap
ChainMap({'a': 1})
>>>cmap.update(b)
>>>cmap
ChainMap({'b': 2, 'a': 1})
>>>cmap.parents
ChainMap({})
>>>cmap1 = collections.ChainMap(a,b)
>>>cmap1
ChainMap({'a': 1}, {'b': 2})
>>>cmap1['b'] = 3 # a
>>>cmap1
ChainMap({'b': 3, 'a': 1}, {'b': 2})
>>>'c' in cmap1
False
>>>cmap1['b'] # 'b'
3
collections.Counter
Counterは、反復可能なオブジェクト内の各要素の出現回数を統計しますが、各要素はhashableでなければなりません.
>>>counter = collections.Counter('abracadabra')
>>>counter
Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
>>>counter.update('aaaaazzz')
>>>counter
Counter({'a': 10, 'z': 3, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
>>>counter.most_common(2)
[('a', 10), ('z', 3)]
collections.UserDict
A pure Python implementation of a mapping that works like a standard dict.これは親として継承されて使用されます.これとdictの大きな違いは、UserDictが自分のデータを露出するselfを直接使うことである.Dataは直接アクセスできますdataは辞書です.たとえば、データのセットにintがあり、str(int)タイプがkeyとしてクエリーにアクセスするため、UserDictを使用して現在の環境で適切な辞書構造を作成できます.
class StrDict(collections.UserDict):
def __missing__(self, key):
if isinstance(key, str):
raise KeyError(key)
return self[str(key)]
def __contains__(self, key):
return str(key) in self.data
def __setitem__(self, key, value): # watch out forever recursion by self[str[key]] = value
self.data[str(key)] = value
>>>sdict = StrDict()
>>>sdict['4'] = 'four'
>>>sdict[5] = 'five'
>>>sdict[1] = 'one'
>>>print(sdict[4])
four
>>>print(sdict['5'])
five
>>>print(sdict['1'])
one
>>>4 in sdict
True
>>>'5' in sdict
True
>>>6 in sdict
False
継承関係StrDict->UserDict->MutableMapping->Mappingを見てみましょう
>>>sdict.update(((2,'two'),(10,'ten'))) # inherited from MutableMapping.update
>>>sdict
{'10': 'ten', '4': 'four', '2': 'two', '5': 'five', '1': 'one'}
>>>sdict.get('5',None) # inherited from Mapping.get
'five'
>>>print(sdict.get('9',None))
None
MutableMapping.update This powerful method can be called directly but is also used by __init__ to load the instance from other mappings, from iterables of (key, value) pairs, and keyword arguments. Because it uses self[key] = value to add items, it ends up calling our implementation of __setitem__. Mapping.get In StrKeyDict, we had to code our own get to obtain results consistent with __getitem__, but in Example 3-8 we inherited Mapping.get, which is implemented exactly like StrKeyDict0.get.
Immutable Mappings
The mapping types provided by the standard library are all mutable, but you may need to guarantee that a user cannot change a mapping by mistake. Since Python 3.3, the types module provides a wrapper class called MappingProxyType, which, given a mapping, returns a mappingproxy instance that is a read-only but dynamic view of the original mapping. This means that updates to the original mapping can be seen in the mappingproxy, but changes cannot be made through it.
>>>import types
>>>d = {'a':1}
>>>d_proxy = types.MappingProxyType(d)
>>>d_proxy
mappingproxy({'a': 1})
>>>d_proxy['a'] = 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-00aea5d4359e> in <module>()
----> 1 d_proxy['a'] = 2
TypeError: 'mappingproxy' object does not support item assignment
>>>d['b'] = 2
>>>d_proxy # dynamic linked
mappingproxy({'b': 2, 'a': 1})
>>>sdict.__dict__
{'data': {'1': 'one', '10': 'ten', '2': 'two', '4': 'four', '5': 'five'}}
>>>sdict.__dict__['m'] = 7
>>>sdict
{'10': 'ten', '4': 'four', '2': 'two', '5': 'five', '1': 'one'}
>>>sdict.__dict__
{'data': {'1': 'one', '10': 'ten', '2': 'two', '4': 'four', '5': 'five'},
'm': 7}
>>>sdict.m
7