What is the output of the following Python program?
d = {"a": 1, "b": 2}
d["c"] = 3
d["a"] = 10
print(d, len(d))
Updating "a" replaces its value and keeps its original position.
Dictionaries · Exercise 2 of 4
Read each Python program and choose what it prints. Every program was run on Python 3, so the answers are the real output.
What is the output of the following Python program?
d = {"a": 1, "b": 2}
d["c"] = 3
d["a"] = 10
print(d, len(d))
Updating "a" replaces its value and keeps its original position.
What is the output of the following Python program?
d = {"a": 10}
print(d.get("z"), d.get("z", 0), "a" in d, 10 in d, 10 in d.values())
get() returns None or the default; in checks keys unless you ask the values() view.
What is the output of the following Python program?
d = {"x": 1, "y": 2, "x": 3}
print(d, len(d))
The second "x" overwrites the value; the key stays where it first appeared.
What is the output of the following Python program?
d = {1: "int", True: "bool", 1.0: "float"}
print(d, len(d))
The three keys are equal with equal hashes, so they are one key. The first key object (1) is kept and each assignment replaces the value, ending with "float".
What is the output of the following Python program?
d = {"a": 1, "b": 2, "c": 3}
print(d.pop("b"), d.popitem(), d, d.pop("z", "none"))
pop returns the value; popitem removes the last inserted pair. pop with a default never raises.
What is the output of the following Python program?
d = {"a": 1}
k = d.keys()
snapshot = list(d.keys())
d["b"] = 2
print(k, snapshot, list(d.values()))
The view k reflects the new key; list() made an independent snapshot before the change.
What is the output of the following Python program?
d = {}
d.setdefault("x", []).append(1)
d.setdefault("x", []).append(2)
print(d, d.setdefault("y", 0))
The second setdefault("x", []) returns the existing list. print receives the dict object itself, and its arguments are evaluated before anything is printed, so the dict already contains "y" when it is shown.
What is the output of the following Python program?
counts = {}
for ch in "banana":
counts[ch] = counts.get(ch, 0) + 1
print(counts)
get(ch, 0) avoids the KeyError on first sight. Keys appear in the order they were first inserted: b, a, n.
What is the output of the following Python program?
a = {"x": 1, "y": 2}
b = {"y": 20, "z": 30}
print(a | b, {**b, **a})
The right side wins for duplicate keys. Key order comes from where each key first appeared: b's keys first in the second merge.
What is the output of the following Python program?
print({n: n * n for n in range(1, 5) if n % 2 == 0}, {v: k for k, v in {"a": 1, "b": 2}.items()})
The filter keeps even n; the second comprehension swaps keys and values.
Timed online tests with instant scores and explanations.