LoginSignup
3
3

More than 5 years have passed since last update.

Python: defaultdictで辞書を使った数え上げをシンプルに

Posted at

概要

defaultdictを使うと、キーが存在しなかった時のデフォルト値を設定できる。

サンプル

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d['key1']
0
>>> d['key2'] += 1
1

要素を数えていくような場合に便利。

>>> from collections import defaultdict
>>> fruits = ['apple', 'banana', 'orange', 'banana', 'apple']
>>> for fruit in fruits:
...     d[fruit] += 1
>>> for k, v in d.items():
...     print(k, v)
...
apple 2
banana 2
orange 1

備考

  • defaultdictは、dictにあるメソッドは使える
  • パフォーマンスに問題があるようなので(未検証)、大量のデータを扱う際は気をつける

ドキュメント

3
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3