This answer key contains 4 multiple-choice, 4 fill-in-the-blank, and 4 output-prediction questions for Python Dictionaries, with the exact answer and a short explanation for every question.
The answers are shown in full, so use this page after making an attempt. The practice page is the better first pass.
How do you read the value stored under the key name?
Answer: data["name"]
Why: Square brackets with the key read a dictionary value.
What does {"a": 1}.get("missing", 0) return?
Answer: 0
Why: get returns the provided default when the key is absent.
What does items() give you in a loop?
Answer: Key-value pairs
Why: items() yields pairs that can be unpacked into key and value.
What is len({"a": 1, "b": 2})?
Answer: 2
Why: The dictionary has two keys.
Complete the method that returns a default for a missing key.
order = {"drink": "latte"}
print(order.____("price", 0))Answer: get
Why: get(key, default) avoids a KeyError for an absent key.
Complete the method that yields key-value pairs.
for key, value in order.____():
print(key, value)Answer: items
Why: items() returns a view of the dictionary's pairs.
Complete the method that reads the current count, or 0 if absent.
counts[drink] = counts.____(drink, 0) + 1Answer: get
Why: The counting pattern uses get(key, 0) before adding one.
Complete the key so the price is printed.
data = {"drink": "latte", "price": 4.5}
print(data["____"])Answer: price
Why: The key in the brackets must match a key in the dictionary.
What does this code print?
print({"a": 1, "b": 2}["b"])Answer: 2
Why: The value under key b is 2.
What does the program output?
print({"a": 1}.get("x", 0))Answer: 0
Why: x is missing, so get returns the default 0.
What appears on the screen?
print(list({"a": 1, "b": 2}.keys()))Answer: ['a', 'b']
Why: keys() returns the dictionary keys in insertion order.
What is printed?
d = {"x": 2}
d["x"] += 3
print(d["x"])Answer: 5
Why: The value starts at 2, then increases by 3.
Try the questions first
Open the practice page for Python Dictionaries and answer the same 12 questions with instant feedback.