Dictionaries · Python example
Count repeated words with a dictionary and print the results in alphabetical order.
Dictionaries map keys to values, which makes them a natural tool for counting. This example builds a frequency table word by word.
text = "the cat and the dog and the bird"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
for word in sorted(counts):
print(f"{word}: {counts[word]}")