value = map.get('hi', 0)
from collections import defaultdict
map = defaultdict(int)
map['a'] += 1
map = defaultdict(list)
map['a'].append('hi')也有一些任务是 setdefault 和 defaultdict 都处理不好的。
例如,我们要写一个程序,在文件系统里管理社交网络账号中的图片。这个程序应该用字典把这些图片的路径名跟相关的文件句柄(file handle)关联起来,这样我们就能方便地读取并写入图像了。下面,先用普通的 dict 实例实现。我们把 get 方法与赋值表达式结合起来,判断字典里有没有当前要操作的这个键。
pictures={}
path = 'profile_1234.png'
if (handle := pictures.get(path)) is None:
try:
handle=open(path,a+b')
except OSError:
print(f'Failed to open path {path}')
raise
else:
pictures[path] = handle
handler.seek(0)
image_data = handle.read()但是上面处理不太优雅,优雅的方式可以采用 __miss__ 构造依赖键的默认值。
class Pictures(dict):
def __missing__(self,key):
value = open_picture(key)
self[key]=value
return value
pictures = Pictures()
handle =pictures[path]
handle.seek(0)
image_data = handle.read()访问 pictures[path] 时,如果 pictures 字典里没有 path 这个键,那就会调用 __missing__ 方法。这个方法必须根据 key 参数创建一份新的默认值,系统会把这个默认值插入字典并返回给调用方。