Home › Learn › Python › Dictionaries, tuples, and sets

Counting things

Lesson 25 of 40. Tally items with a dictionary, then meet Counter.

Counting how often each thing appears is a dictionary whose values are counts: for each item, counts[item] = counts.get(item, 0) + 1. That pattern is so common that the standard library ships it: from collections import Counter, then Counter(words) builds the same dictionary and .most_common(1) returns the top entry as a list of (item, count) pairs.

Normalize before counting, or "The" and "the" become two words. In the final project that job belongs to clean_words, which hands this function a list of lower-case words with the punctuation already stripped; here the lists are clean to begin with.

from collections import Counter
c = Counter("mississippi")
print(c["s"])              # 4
print(c.most_common(1))    # [('i', 4)] or [('s', 4)]

Your task

Write word_counts(words) that returns a dictionary of word to count for a list of words, in the order the words first appear. Then write most_common_word(words) returning the word that appears most often; when several tie, the first of them to reach that count, which is what max gives on a dictionary filled in order.

Part of the final project. word_counts turns the list of words into a dictionary of word to count. It is saved in this browser and loaded into Project: text statistics when you get there.

Hint 1

for word in words: counts[word] = counts.get(word, 0) + 1

Hint 2

counts = word_counts(words); return max(counts, key=counts.get)

Show the solution
def word_counts(words):
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    return counts


def most_common_word(words):
    counts = word_counts(words)
    return max(counts, key=counts.get)

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.