@ Introducing Python: Modern Computing in Simple Packages by Bill Lubanovic
(No. 3136 / 12833)
defaultdictについて紹介されていた。
引数に関数を与えて、辞書の内容を初期化するようだ。
参考:
Python » ドキュメント » Python 標準ライブラリ » 8. データ型 »
8.3.4.1. defaultdict の使用例
カウンタ
試してみた。
import collections
word_counter = collections.defaultdict(int)
for word in ['daemon', 'demon', 'demoon', 'demon', 'demon', 'daemon']:
word_counter[word] += 1
print(word_counter)
run
defaultdict(<class 'int'>, {'demoon': 1, 'daemon': 2, 'demon': 3})
同じ処理はCounter()
を使っても可能とのこと。
@ 3184
試してみた。
http://ideone.com/CSKsOO
import collections
wordlist = ['daemon', 'demon', 'demoon', 'demon', 'demon', 'daemon']
word_counter = collections.Counter(wordlist)
print(word_counter)
run
Counter({'demon': 3, 'daemon': 2, 'demoon': 1})
key, valueペアのシーケンスを辞書グループ化
defaultdictを使って、(key, value)ペアのシーケンスをリストの辞書へグループ化している例がある。
import collections
seq = [('7of9', 47), ('Janeway', 314), ('Kim', 2718), ('7of9', 6022)]
dct = collections.defaultdict(list)
print(seq)
for key, value in seq:
dct[key].append(value)
print(dct.items())
run
[('7of9', 47), ('Janeway', 314), ('Kim', 2718), ('7of9', 6022)]
dict_items([('Janeway', [314]), ('7of9', [47, 6022]), ('Kim', [2718])])