Intermediate · Dictionaries · 135 of 264
Phone book
Read a phone book, then answer questions about it.
Input: n, then n lines "name number", then m, then m names to look up. Output: for each name, its number or not found
Examples
Input
2 ann 555-1234 bob 555-9876 3 bob carl ann
Output
555-9876 not found 555-1234
Input
1 zoe 1 1 Zoe
Output
not found
One more test checks other inputs when you press Check.
Stuck? The idea behind dictionaries
A dictionary links keys to values, like words to meanings: ages["Ann"] = 12. Looking up a key is fast, however big it is.
.get(key, 0) gives a default when the key isn't there; looping over a dictionary gives its keys, .items() gives keys and values together.
counts = {}
for word in input().split():
counts[word] = counts.get(word, 0) + 1
for word, n in counts.items():
print(word, n)Watch for: Reading a key that isn't there stops the program with a KeyError: check with in, or use .get().