Pythonのある生活

Pythonの勉強を始めたインフラエンジニアです。インフラエンジニアって、プログラミング全く使わないΣ( ゚Д゚)ノ!ので、独学の勉強日記です。現在は、Progate、Aidemyを使っています。

defaultdictの使い方

defaultdict( 型 )

辞書配列を繰り返し(for)を使って作成したい!

同じキーは一つにまとめたい!

というときに使えるdefaultdict。

 

使い方はちょっと複雑。

 

【対話コード】

>>>from collections import defaultdict

>>>word1 = "sasakama"

>>>d = defaultdict(int)

>>>for x in word1:

...    d[x] += 1  #最初に4つの空白

...

>>>print(d)

defaultdict(<class 'int'>, {'s': 2, 'a': 4, 'k': 1, 'm': 1})

 

 

とりあえず、笹かまの構成文字を数えてみました。

インポートするときはcollectionから!

defaultdict 使い方が難しいんですよねー

自分もまだよくわかっていない。。。