Learn / Python / Dictionaries: counting words

Python, lesson 6 of 6

Dictionaries: counting words

A dictionary stores pairs: a key and its value. It is perfect for counting:

stock = {"bolt": 12, "nut": 40}
stock["washer"] = 5          # add a key
stock["bolt"] = stock["bolt"] + 1
print(stock["bolt"])        # 13
print("nut" in stock)       # True

Text can be split into words with .split() and made lowercase with .lower().

Your turn

Write word_counts(text) that returns a dictionary of how many times each word appears. Treat capitals as the same word ("Bolt" and "bolt" count together).

Press Run to see what your code prints.