defaultdict是dict的一个子类,接受一个工厂函数作为参数,当访问defaultdict中不存在的key时,会将工厂函数的返回值作为默认的value。
class defaultdict(dict): """ defaultdict(default_factory[, ...]) --> dict with default factory The default factory is called without arguments to produce a new value when a key is not present, in __getitem__ only. A defaultdict compares equal to a dict with the same items. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments. """
测试代码
完整代码:
__author__ = 'blackmatrix'def factory_func(): return 'default_factory'test_defaultdict = defaultdict(factory_func)if __name__ == '__main__': ''' 当key存在时,返回的是key对应的value 这个时候和普通的dict没有什么区别 ''' test_defaultdict['a'] = '233333' print(test_defaultdict['a']) ''' 当访问不存在的key时,自动将工厂函数的返回值作为默认值 ''' print(test_defaultdict['b']) print(test_defaultdict['c'])
运行结果
233333default_factorydefault_factory
如果defaultdict在创建的时候没有传入工厂函数,则在访问不存在的key时,会抛出KeyError
from collections import defaultdicttest_defaultdict2 = defaultdict()print(test_defaultdict2['x'])# KeyError: 'x'