1、以一個例子開始:統(tǒng)計一個列表里各單詞重復(fù)次數(shù)
words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter[kw] += 1
這樣寫肯定會報錯的,因為各詞的個數(shù)都沒有初始值,引發(fā)KeyError
2、改進一下:加入if判斷
words = ['hello','world','nice','world']counter = dict()forkwinwords:ifkwinwords:? ? ? ? counter[kw] += 1else:? ? ? ? counter[kw] = 0
3、再改進:使用setdefault()方法設(shè)置默認值
words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter.setdefault(kw, 0)? ? counter[kw] += 1
setdefault(),需提供兩個參數(shù),第一個參數(shù)是鍵值,第二個參數(shù)是默認值,每次調(diào)用都有一個返回值,如果字典中不存在該鍵則返回默認值,如果存在該鍵則返回該值,利用返回值可再次修改代碼。
words = ['hello','world','nice','world']counter = dict()forkwinwords:? ? counter[kw] = counter.setdefault(kw, 0) + 1
4、接著改進
一種特殊類型的字典本身就保存了默認值defaultdict(),defaultdict類的初始化函數(shù)接受一個類型作為參數(shù),當(dāng)所訪問的鍵不存在的時候,可以實例化一個值作為默認值。
from collections import defaultdictdd = defaultdict(list)defaultdict(, {})#給它賦值,同時也是讀取dd['h'h]defaultdict(, {'hh': []})dd['hh'].append('haha')defaultdict(, {'hh': ['haha']})
該類除了接受類型名稱作為初始化函數(shù)的參數(shù)之外,還可以使用任何不帶參數(shù)的可調(diào)用函數(shù),到時該函數(shù)的返回結(jié)果作為默認值,這樣使得默認值的取值更加靈活。
>>> from collections import defaultdict>>>defzero():...? ? return0...>>> dd = defaultdict(zero)>>> dddefaultdict(, {})>>> dd['foo']0>>> dddefaultdict(, {'foo':0})
最終代碼:
fromcollectionsimportdefaultdictwords = ['hello','world','nice','world']#使用lambda來定義簡單的函數(shù)counter = defaultdict(lambda:0)forkwinwords:? ? counter[kw] +=1