ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
d = {1: "a", 2: "b"}
for k in d:
    d[k] = d[k] * 2
try:
    for k in d:
        d[k * 10] = "x"
except RuntimeError:
    print("RE", end=" ")
print(len(d), d[2])
  1. A. RE 4 bb
  2. B. RE 3 bb
  3. C. 4 bb
  4. D. RE 3 b

Correct answer: B. RE 3 bb

Replacing the value of an existing key does not change the dict's size, so the first loop is safe and doubles the values ("aa", "bb"). In the second loop the first iteration inserts key 10; when the loop asks for the next key, CPython notices the size changed and raises RuntimeError. Only one key was added, so len is 3.

More Python Programming questions

Exams that ask this topic