Python collections.defaultdict()使用

參考:
Documentation

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 dictclass and is not documented here.

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 Examples

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:

>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
...     d[k].append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

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():

>>> d = {}
>>> for k, v in s:
...     d.setdefault(k, []).append(v)
...
>>> sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

A faster and more flexible way to create constant functions is to use a lambda function which can supply any constant value (not just zero):

>>> def constant_factory(value):
...     return lambda: value
>>> d = defaultdict(constant_factory('<missing>'))
>>> d.update(name='John', action='ran')
>>> '%(name)s %(action)s to %(object)s' % d
'John ran to <missing>'

Setting the default_factory to set makes the defaultdict useful for building a dictionary of sets:

>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
...     d[k].add(v)
...
>>> sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末振亮,一起剝皮案震驚了整個濱河市户敬,隨后出現(xiàn)的幾起案子遏弱,更是在濱河造成了極大的恐慌改备,老刑警劉巖贾漏,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件敷燎,死亡現(xiàn)場離奇詭異键俱,居然都是意外死亡建椰,警方通過查閱死者的電腦和手機获雕,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門薄腻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人届案,你說我怎么就攤上這事庵楷。” “怎么了?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵尽纽,是天一觀的道長咐蚯。 經(jīng)常有香客問我,道長弄贿,這世上最難降的妖魔是什么春锋? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮差凹,結(jié)果婚禮上期奔,老公的妹妹穿的比我還像新娘。我一直安慰自己危尿,他們只是感情好呐萌,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著脚线,像睡著了一般搁胆。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上邮绿,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天渠旁,我揣著相機與錄音,去河邊找鬼船逮。 笑死顾腊,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的挖胃。 我是一名探鬼主播杂靶,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼酱鸭!你這毒婦竟也來了吗垮?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤凹髓,失蹤者是張志新(化名)和其女友劉穎烁登,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蔚舀,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡饵沧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了赌躺。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片狼牺。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖礼患,靈堂內(nèi)的尸體忽然破棺而出是钥,到底是詐尸還是另有隱情掠归,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布悄泥,位于F島的核電站拂到,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏码泞。R本人自食惡果不足惜兄旬,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望余寥。 院中可真熱鬧领铐,春花似錦、人聲如沸宋舷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽祝蝠。三九已至音诈,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間绎狭,已是汗流浹背细溅。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留儡嘶,地道東北人喇聊。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像蹦狂,于是被迫代替她去往敵國和親誓篱。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容