Counting with a Dictionary
You can use a dictionary to count how many times each value appears. Use the value as the key, and store its count as that key's value.
letters = "balloon"
counts = {}
for letter in letters:
if letter in counts:
counts[letter] += 1
else:
counts[letter] = 1
print(counts)
Output:
{'b': 1, 'a': 1, 'l': 2, 'o': 2, 'n': 1}
The first time a letter appears, the else part adds it as a new key with a count of 1. Each time the letter appears again, its count goes up by 1. The keys stay in the order in which each letter first appeared.
With get and a fallback of 0, you can handle both cases in one line:
letters = "balloon"
counts = {}
for letter in letters:
counts[letter] = counts.get(letter, 0) + 1
print(counts)
Output:
{'b': 1, 'a': 1, 'l': 2, 'o': 2, 'n': 1}
When a letter is new, get returns 0, so its count becomes 1. When the letter is already there, get returns its current count, and the line adds 1 to it.
Python's built-in modules also include collections.Counter, which does this counting for you. It still helps to write the loop yourself once, so you see what Counter does.
In the exercise, count each word and print the report.