Read a line of lowercase words and print how many times each different word appears, in the order the words first appear.
What to build
A tally made with a dictionary, printed in first-seen order.
Requirements
- Read the line.
- Print each different word and its count, in order of first appearance.
Input
One line of words separated by spaces.
Output
One line per different word: the word, a space, and its count.
Constraints
There are at most 1000 words.
Example
Input:
a b a c b a
Output:
a 3
b 2
c 1
Why it works
Dictionaries remember the order in which keys were added, so printing them gives first-seen order with no extra work.
Examples
Example 1 · Input
a b a c b a
Expected output
a 3 b 2 c 1
Example 2 · Input
hello
Expected output
hello 1
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
counts.get(w, 0) + 1 adds one to the count.
Hint 2
A dictionary keeps keys in the order they were added.
Solution
Show one correct solution (try it yourself first)
words = input().split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
for w, c in counts.items():
print(w, c)