defaultdict 可以帮助我们初始化,它的参数作为 default_factory
DefaultDict 是一个被初始化的字典,也就是每个键都已经被访问一次:
In [53]: d = defaultdict(int)
In [54]: for k in ‘collections’:
…: d[k] += 1
In [55]: d
Out[55]:
defaultdict(int,
{‘c’: 2, ‘o’: 2, ‘l’: 2, ‘e’: 1, ‘t’: 1, ‘i’: 1, ‘n’: 1, ‘s’: 1})
一般地,当你尝试访问一个不在字典中的值时,将会抛出一个异常。但是 defaultdict 可以帮助我们初始化,它的参数作为 default_factory. 在上面例子中,将生成 int 对象,意思是默认值为 int 型,并设定初始值为 0,所以我们可以很容易地统计每个字符出现的次数。
Simple and clean!
更有用的一个使用场景,我们有很多种商品,在每秒内下单次数的统计数据如下:
In [56]: data = [(‘iphone11’,103), (‘华为 macbook-SKU1232’,210),(‘iphone11’,21),(‘
…: 华为 macbook-SKU1232′,100)]
In [57]: d = defaultdict(list)
In [58]: for ele in data:
…: d[ele[0]].append(ele[1])
In [59]: d
Out[59]: defaultdict(list, {‘iphone11’: [103, 21], ‘华为 macbook-SKU1232’: [210, 100]})
上面例子 default_dict 取值为 list, 因此,我们可以立即 append 一个元素到 list 中,更简洁。
总结
至此,你已经了解 collections 库中的 DefaultDict 类型,它确实太好用,大家可以操练起来!