Python dictionaries and frequency counting

A dictionary maps each distinct key to a value. get(key, 0) supplies zero when a word has not appeared yet, then the count is incremented.

Python
counts = {}
for word in "red blue red".split():
    counts[word] = counts.get(word, 0) + 1
for word in sorted(counts):
    print(word, counts[word])
assert counts.get("green", 0) == 0
Read the full lesson