Python Snippet

Counter for Frequency Counting

Difficulty: Easy

`collections.Counter` is the dict-of-counts that every other 'count occurrences' implementation tries to be. It supports increment-by-add, most-common-K, and arithmetic between counters. This snippet covers the basic frequency count, the most-common-K shortcut, and the multiset arithmetic that makes Counter the right choice for inventory math and difference reports.

Code Snippets
/

Counter for Frequency Counting

Counter for Frequency Counting

`collections.Counter` is the dict-of-counts that every other 'count occurrences' implementation tries to be. It supports increment-by-add, most-common-K, and arithmetic between counters. This snippet covers the basic frequency count, the most-common-K shortcut, and the multiset arithmetic that makes Counter the right choice for inventory math and difference reports.

Python
Easy
3 snippets
py-collections
py-standard-library
code-template
hash-table

1,106 views

25

Passing an iterable to Counter produces a dict-like object where each value is the number of times the key appeared. Counter extends dict, so all dict methods work, but missing keys return 0 instead of raising. update(iterable) increments counts (it does not overwrite, unlike a normal dict update). This is the fastest way to compute character histograms, log-line frequencies, or anagram-equality checks: two strings are anagrams iff their Counters are equal.