import collections import re WORD_RE = re.compile(r'\w+') index = collections.defaultdict(list) #用list方法作为默认工厂创建一个默认字典 with open('xx.txt',encoding='utf-8') as fp: for line_no,line in enumerate(fp,1): for match in WORD_RE.findeiter(line): word = match.group() column_no = match.start()+1 location = (line_no,column_no) index[word].append(location) # 如果index没有Word记录,会调用默认工厂,创建一个空列表 for word in sorted(index,key=str.upper): print(word,index[word])
import collections class StrKeyDict(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,item): self.data[str(key)] = item
不可变映射类型
import collections from types import MappingProxyType d = {1:'A'} d_proxy = MappingProxyType(d) d_proxy[1] # A d_proxy[2] #报错因为不可变 d_proxy[2] = 'B' #{1:'A',2:'B'}