🤖

python 辞書で最も多く出現したkeyの数を取得する counterの使い方

に公開

Counterを使わずに最も多い要素を取得しようとすると、以下のようなコードが必要でした。

#愚直にやる方法:forループ + 辞書
fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count_dict = {}
for fruit in fruits:
    if fruit in count_dict:
        count_dict[fruit] += 1
    else:
        count_dict[fruit] = 1
max_count = 0
most_common_item = None
for item, count in count_dict.items():
    if count > max_count:
        max_count = count
        most_common_item = item

print(f"最も多い要素: {most_common_item}, 出現回数: {max_count}")
# 最も多い要素: apple, 出現回数: 3

これが10行以上必要だったものが、Counterを使えばたった3行で実現できます。

from collections import Counter

fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(fruits)
most_common_item, max_count = counter.most_common(1)[0]

print(f"最も多い要素: {most_common_item}, 出現回数: {max_count}")
# 最も多い要素: apple, 出現回数: 3

Counterの3つのメリット

1. コードが短く読みやすい

カウント処理が1行で完結
意図が明確で保守しやすい

2. エラーが起きにくい

キーの存在チェックが不要
初期化漏れの心配がない

3. 機能が豊富

most_common()で簡単にランキング取得
辞書のように扱える(counter['apple']でカウント取得)
Counterオブジェクト同士の演算も可能

Counterオブジェクトの作成

from collections import Counter

Discussion