Answer key · 12 questions

Python Dictionaries Exercises With Answers

All 12 questions for Python Dictionaries in one place. Try the practice page first, then use this page to check the exact answer and the reason.

Quick answer

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.

01 · Multiple choice

How do you read the value stored under the key name?

  1. data["name"]correct
  2. data[name]
  3. data(name)
  4. data.name

Answer: data["name"]

Why: Square brackets with the key read a dictionary value.

02 · Multiple choice

What does {"a": 1}.get("missing", 0) return?

  1. None
  2. "missing"
  3. 0correct
  4. KeyError

Answer: 0

Why: get returns the provided default when the key is absent.

03 · Multiple choice

What does items() give you in a loop?

  1. Key-value pairscorrect
  2. Only the values
  3. A sorted copy
  4. Only the keys

Answer: Key-value pairs

Why: items() yields pairs that can be unpacked into key and value.

04 · Multiple choice

What is len({"a": 1, "b": 2})?

  1. 2correct
  2. 3
  3. 1
  4. 4

Answer: 2

Why: The dictionary has two keys.

05 · Fill in the blank

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.

06 · Fill in the blank

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.

07 · Fill in the blank

Complete the method that reads the current count, or 0 if absent.

counts[drink] = counts.____(drink, 0) + 1

Answer: get

Why: The counting pattern uses get(key, 0) before adding one.

08 · Fill in the blank

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.

09 · Predict output

What does this code print?

print({"a": 1, "b": 2}["b"])

Answer: 2

Why: The value under key b is 2.

10 · Predict output

What does the program output?

print({"a": 1}.get("x", 0))

Answer: 0

Why: x is missing, so get returns the default 0.

11 · Predict output

What appears on the screen?

print(list({"a": 1, "b": 2}.keys()))

Answer: ['a', 'b']

Why: keys() returns the dictionary keys in insertion order.

12 · Predict output

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.

Practice this lesson