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


在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)]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM