Python3 collections.defaultdict()与dict的使用和区别
前言:在Python里面有一个模块collections,解释是数据类型容器模块,这里面有一个collections.defaultdict()经常被用到
综述
这里的defaultdict(function_factory)
构建的是一个类似dictionary的对象,其中keys的值,自行确定赋值;但是values的类型,是function_factory
的类实例,而且具有默认值。比如defaultdict(int)则创建一个类似dictionary对象,里面任何的values都是int的实例,而且就算是一个不存在的key,d[key]也有一个默认值,这个默认值是int()的默认值0。
解释与使用
简短解释
defaultdict
dict subclass that calls a factory function to supply missing values(这是一个简短的解释,defaultdict属于内建函数dict的子类,调用工厂函数提供缺失的值)
针对工厂函数来自pythn编程的核心解释
python 2.2统一了类型和类,所有的内建类型现在也都是类,在这基础之上,原来的内建转换函数诸如int()
,type()
,list()
等,现在都成了工厂函数。也就是说它们看上去有点像函数,但它们的实质是类。当你调用它们的时候,实际上是生成了该类型的一个实例,就像工厂产生货物一样
使用
来看一下下面这段代码:
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
d[key].append(v)
list(d.items())
这里就开始有点明白了,原来defaultdict可以接受一个内建函数list作为参数。其实呢,list()本身是内建函数,但是经过更新之后,python里面所有东西都是对象,所以list改编成了类,引入list的时候产生了一个类的实例。
还是不太明白,再看defaultdict的help解释
class collections.defaultdict([default_factory[,...]])
Returns a new dictionary-like object.defaultdict is a subclass of the built-in class.It overrides one method and adds one writable instance variable.The remaining functionality is the same as for the dict class and is not documented here.
首先说明,collections.defaultdictionary会返回一个类似dictionary的对象。这个defaultdict类和dict类几乎是一样的,除了它重载了一个方法和增加了一个可写的实例变量。
The first argument provides the initial value for the default_factory attribute.it defaults to None.If default_factory is not None,it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned
看以下代码示例:
import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
# defaultdict
d = collections.defaultdict(list)
for k, v in s:
d[k].append(v)
# use dict and setdefault
g = {}
for k, v in s:
g.setdefault(k, []).append(v)
# Use dict
e={}
for k, v in s:
e[k] = v
结果输出如下:
list(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> list(g.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> list(e.items())
[('blue', 4), ('red', 1), ('yellow', 3)]
>>> d
defaultdict(<class 'list'>, {'blue': [2, 4], 'red': [1], 'yellow': [1, 3]})
>>> g
{'blue': [2, 4], 'red': [1], 'yellow': [1, 3]}
>>> e
{'blue': 4, 'red': 1, 'yellow': 3}
>>> d.items()
dict_items([('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])])
>>> d["blue"]
[2, 4]
>>> d.keys()
dict_keys(['blue', 'red', 'yellow'])
>>> d.default_factory
<class 'list'>
>>> d.values()
dict_values([[2, 4], [1], [1, 3]])
用法总结
- collections.defaultdict(list)使用起来效果和运用dict.setdefault()比较类似。官网也说了,这种方法和
dict.setdefault()
等价,但是要更快