Paul's Python CoursePPC

Counting with Counter

Not met yet

Counter from collections counts things for you. Hand it a list and it gives back a kind of dictionary: each different item, with how many times it turned up. Something it never saw counts as 0, not an error. .most_common(3) gives the three commonest as (item, count) pairs, commonest first, and things with the same count stay in the order they were first seen. Hand it a string and it counts the letters, so split the text into words first.

Try it

main.py
from collections import Counter

orders = ["tea", "coffee", "tea", "hot chocolate", "tea", "coffee"]
counts = Counter(orders)
print(counts["tea"], counts["juice"])
print(counts.most_common(2))

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks a Counter raises a KeyError for something it hasn't counted, the way a dictionary does.
  • Thinks a Counter gives None for something it hasn't counted, when it gives 0.
  • Thinks most_common puts things in alphabetical order rather than commonest first.
  • Thinks Counter given a string counts its words, when it counts its characters.

Where it comes up