Python collections.defaultdict() 與 dict的使用和區別

pythontab發表於2013-10-23

在Python裡面有一個模組collections,解釋是資料型別容器模組。這裡面有一個collections.defaultdict()經常被用到。主要說說這個東西。

綜述:

這裡的defaultdict(function_factory)構建的是一個類似dictionary的物件,其中keys的值,自行確定賦值,但是values的型別,是function_factory的類例項,而且具有預設值。比如default(int)則建立一個類似dictionary物件,裡面任何的values都是int的例項,而且就算是一個不存在的key, d[key] 也有一個預設值,這個預設值是int()的預設值0.

defaultdict

dict subclass that calls a factory function to supply missing values。

這是一個簡短的解釋

defaultdict屬於內建函式dict的一個子類,呼叫工廠函式提供缺失的值。

比較暈,什麼是工廠函式:

來自python 核心程式設計的解釋

Python 2.2 統一了型別和類, 所有的內建型別現在也都是類, 在這基礎之上, 原來的

所謂內建轉換函式象int(), type(), list() 等等, 現在都成了工廠函式。 也就是說雖然他

們看上去有點象函式, 實質上他們是類。當你呼叫它們時, 實際上是生成了該型別的一個實

例, 就象工廠生產貨物一樣。

下面這些大家熟悉的工廠函式在老的Python 版裡被稱為內建函式:

int(), long(), float(), complex()

str(), unicode(), basestring()

list(), tuple()

type()

以前沒有工廠函式的其他型別,現在也都有了工廠函式。除此之外,那些支援新風格的類

的全新的資料型別,也新增了相應的工廠函式。下面列出了這些工廠函式:

dict()

bool()

set(), frozenset()

object()

classmethod()

staticmethod()

super()

property()

file()

再看看它的使用:

import collections
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = collections.defaultdict(list)
for k, v in s:
    d[k].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 dict 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.defaultdict會返回一個類似dictionary的物件,注意是類似的物件,不是完全一樣的物件。這個defaultdict和dict類,幾乎是一樣的,除了它過載了一個方法和增加了一個可寫的例項變數。(可寫的例項變數,我還是沒明白)

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

defaultdict objects support the following method in addition to the standard dict operations:

__missing__(key)

If the default_factory attribute is None, this raises a KeyError exception with the key as argument.

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.

主要關注這個話,如果default_factory不是None, 這個default_factory將以一個無引數的形式被呼叫,提供一個預設值給___missing__方法的key。 這個預設值將作為key插入到資料字典裡,然後返回。

十分暈。有扯出了個__missing__方法,這個__missing__方法是collections.defaultdict()的內建方法。

If calling default_factory raises an exception this exception is propagated unchanged.

This method is called by the __getitem__() method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__().

Note that __missing__() is not called for any operations besides __getitem__(). This means that get() will, like normal dictionaries, return None as a default rather than using default_factory.

defaultdict objects support the following instance variable:

default_factory

This attribute is used by the __missing__() method; it is initialized from the first argument to the constructor, if present, or to None, if absent.

看樣子這個文件是難以看懂了。直接看示例:

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())
##list(g.items())
##list(e.items())


看看結果

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()比較相似

python help上也這麼說了

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created using the default_factory function which returns an empty list. The list.append() operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) and the list.append() operation adds another value to the list. This technique is simpler and faster than an equivalent technique using dict.setdefault():

說這種方法會和dict.setdefault()等價,但是要更快。

有必要看看dict.setdefault()

setdefault(key[, default])

If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

如果這個key已經在dictionary裡面存著,返回value.如果key不存在,插入key和一個default value,返回Default. 預設的defaults是None.

但是這裡要注意的是defaultdict是和dict.setdefault等價,和下面那個直接賦值是有區別的。從結果裡面就可以看到,直接賦值會覆蓋。

從最後的d.values還有d[“blue”]來看,後面的使用其實是和dict的用法一樣的,唯一不同的就是初始化的問題。defaultdict可以利用工廠函式,給初始keyi帶來一個預設值。

這個預設值也許是空的list[]  defaultdict(list), 也許是0, defaultdict(int).

再看看下面的這個例子。

defaultdict(int) 這裡的d其實是生成了一個預設為0的帶key的資料字典。你可以想象成 d[key] = int default (int工廠函式的預設值為0)

d[k]所以可以直接讀取 d[“m”] += 1 就是d[“m”] 就是預設值 0+1 = 1

後面的道理就一樣了。

>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
...     d[k] += 1
...
>>> list(d.items())
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]



相關文章