liveBook · Manning

Counter

As explained in Python Workout: 50 ten-minute exercises

Counter is a dictionary subclass in Python's standard library that maps hashable objects to their integer counts.

Use Counter from Python’s collections module when a sequence needs item frequencies. It behaves like a dictionary while providing counting-oriented operations such as most_common. section 3.17 section 3.26

words = ['this', 'is', 'an', 'elementary', 'test', 'example']

Start with a word list and compare each word by the frequency of its most repeated letter. section 3.16

Find the strongest repeated letter

Counter('abcabcabbbc') produces counts for each letter. most_common(1) returns [('b', 5)], so [0][1] extracts the highest count. Wrap that operation in a key function, then let max choose the word with the greatest result. section 3.17 section 3.17

Useful patterns include:

  • Counter(word).most_common(1)[0][1] returns a word’s most frequent letter count. section 3.17
  • most_common() returns descending name-and-count tuples; passing n limits the result to n items. section 3.17

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains construction, dictionary inheritance, most_common results, limiting, indexing, and composition with max.
Examples
Uses words and letters, Counter('abcabcabbbc'), most_common outputs, and a most-repeating-word function.
What it assumes
Assumes familiarity with sequences, dictionaries, functions, indexing, and max key functions.
What you can do after
Apply it via collections.Counter to count sequence items and rank them with most_common.
How it connects
Connects Counter with dictionaries, sequences, lists, tuples, functions, and max.

Also explained in

Compare how 3 books explain Counter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.