Exercises
Dictionaries
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print the name, then look up a missing key without crashing.
Python
person = {"name": "Ada"}
# print the name, then the age as 'unknown'
get() takes a default.
person = {"name": "Ada"}
print(person["name"])
print(person.get("age", "unknown"))Exercise 2Passed
Print each key and value on its own line as key = value.
Python
person = {"name": "Ada", "born": 1815}
# print each pair
items() gives both at once.
person = {"name": "Ada", "born": 1815}
for key, value in person.items():
print(key, "=", value)Exercise 3Passed
Count how many times each word appears, without importing anything.
Python
words = ["a", "b", "a", "c", "a"]
counts = {}
# fill counts
print(counts)get() with a default of 0 makes the increment safe on the first sighting.
words = ["a", "b", "a", "c", "a"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)