2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

collectionsモジュールの実用パターン集:Counter・defaultdict・dequeの真価

Posted at

概要

Pythonの標準ライブラリ collections モジュールは、
汎用データ構造をより柔軟・効率的に扱うためのツールキットである。

本稿では特に使用頻度の高い以下3種:

  • Counter
  • defaultdict
  • deque

これらの実用パターンと設計意図を深掘りし、
「辞書以上に辞書らしく、リスト以上にリストらしい」構造の本質に迫る。


1. Counter:出現回数の集計に特化した辞書

from collections import Counter

words = ["apple", "banana", "apple", "orange", "banana", "apple"]
c = Counter(words)

print(c)  # Counter({'apple': 3, 'banana': 2, 'orange': 1})

✅ 主なメソッド

c.most_common(2)     # → [('apple', 3), ('banana', 2)]
c["banana"] += 1     # カウント操作も直感的
del c["orange"]      # 削除も辞書感覚

→ テキスト分析・ログ解析・カテゴリ集計などに極めて有効


2. defaultdict:キーが存在しない場合の動的初期化

from collections import defaultdict

d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
d["b"].append(3)

print(d)  # {'a': [1, 2], 'b': [3]}
  • dict であれば KeyError が出る場面も、型指定で初期化回避
  • list, set, int, float などがよく使われる

✅ 実務的パターン:逆インデックスの構築

index = defaultdict(set)

data = {
    "alice": ["python", "react"],
    "bob": ["python", "aws"],
}

for user, skills in data.items():
    for skill in skills:
        index[skill].add(user)

# → {'python': {'alice', 'bob'}, 'react': {'alice'}, 'aws': {'bob'}}

3. deque:両端キュー、高速なキュー/スタック構造

from collections import deque

q = deque()
q.append("first")
q.append("second")
q.appendleft("zero")

print(q)  # deque(['zero', 'first', 'second'])

q.pop()       # → 'second'
q.popleft()   # → 'zero'

✅ 特徴

  • 両端操作が O(1) 時間で可能
  • リストの .insert(0, x) のような O(n) 操作を回避できる
  • スライディングウィンドウ, 固定長ログ, LRU実装 に最適

4. 組み合わせによるパターン構築

✅ defaultdict × Counter

nested = defaultdict(Counter)

nested["user1"]["python"] += 1
nested["user1"]["python"] += 1
nested["user1"]["react"] += 1

# → defaultdict(Counter({'python': 2, 'react': 1}))

ユーザー × スキル頻度 のような多次元集計にも対応


✅ deque with maxlen:固定サイズバッファ

window = deque(maxlen=3)
for i in range(5):
    window.append(i)
    print(list(window))

# 出力:
# [0]
# [0, 1]
# [0, 1, 2]
# [1, 2, 3]
# [2, 3, 4]

→ リングバッファや過去N件保持などに最適


よくある誤解と対策

❌ Counterは単なるdictのラッパー?

→ ✅ メソッドやパターンが明確に設計されており、**明示的な“数え上げの意図”**をコードに埋め込める


❌ defaultdictはパフォーマンスが落ちる?

→ ✅ 通常のdictと同等。むしろ冗長な条件分岐が不要になることでトータル効率が向上


❌ dequeは単なる珍しい構造体?

→ ✅ Pythonにおける最適なFIFO/LIFO実装
→ スレッドセーフかつ高負荷処理にも耐えるため、意図的に採用すべき場面がある


結語

collections モジュールは、**Pythonにおける“辞書やリストの限界を拡張する構造群”**である。

  • Counter → 集計処理の明文化
  • defaultdict → 冗長性の排除と構造の自動化
  • deque → 双方向性と時間計算量の最適化

Pythonicとは、“データの形と処理の意図を構造で表現する”ことであり、
collectionsはその設計を明快に体現する標準の武器である。

2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?