from collections.abc import Mapping, MutableMapping
my_dict = {}
print(isinstance(my_dict, Mapping))
print(isinstance(my_dict, MutableMapping))
[Out]
True
True
index= {}
occurences = index.get(word,[])
occurences.append(location)
index[word] = occurrences
这三行代码可以简写为一行
index = {}
index.setdefault(word,[]).append(location)
虽然两者结果是一样的,但是三行代码的那种至少要经过两次键查询,而一行代码的只需要一次键查询。
index = collections.defaultdict(list)
index[word].append(location)
defaultdict里的default_factory属性通过defaultdict的构造方法赋值,并且只有在getitem中被调用,在其他地方如get(k)时不发生作用,没有还是返回默认None。
import collections
class strKeyDict(collections.UserDict):
def __missing__(self, key):
if isinstance(key, str):
raise KeyError
# 如果不加判断当键不存在的时候会无限递归
return self[str(key)]
def __contains__(self, key):
return str(key) in self.data
def __setitem__(self, key, value):
self.data[str(key)] = value
import builtins
from collections import ChainMap
pylookup = ChainMap(locals(), globals(), vars(builtins))
import collections
ct1 = collections.Counter('fafdsfdfadfsdf')
print(ct1)
ct1.update('aaaaaa')
print(ct1)
print(ct1.most_common(2))
ct2 = collections.Counter(a=3, b=4)
print(ct2)
ct = ct1 + ct2
print(ct)
[Out]
Counter({'f': 6, 'd': 4, 'a': 2, 's': 2})
Counter({'a': 8, 'f': 6, 'd': 4, 's': 2})
[('a', 8), ('f', 6)]
Counter({'b': 4, 'a': 3})
Counter({'a': 11, 'f': 6, 'd': 4, 'b': 4, 's': 2})
from types import MappingProxyType
d = {1: 'A'}
d_proxy = MappingProxyType(d)
print(d_proxy)
# [Out] {1: 'A'}
print(d_proxy[1])
# [Out] A
# d_proxy[2] = 'x'
# TypeError: 'mappingproxy' object does not support item assignment
d[2] = 'B'
print(d_proxy)
# [Out] {1: 'A', 2: 'B'}
print(d_proxy[2])
# B
from dis import dis
dis('{1}')
dis('set([1])')
输出
也就是说用字面量直接调用BUILDSET字节码,代替了3个操作:LOADNAME,BUILDLIST,CALLFUNCTION. set的抽象形式接口定义在collections.abc.Set和collections.abc.MultipleSet中。