Data Structures & AlgorithmsHardAmazon · Microsoft OA

Edge case: changing a dict while iterating over it.

Edge case: changing a dict while iterating over it.
d = {1: 'a', 2: 'b', 3: 'c'}
try:
    for k in d:
        if k == 2: d[4] = 'd'
    print("ok", len(d))
except Exception as e:
    print(type(e).__name__)
What is printed?
  1. A. ok 4
  2. B. ok 3
  3. C. KeyError
  4. D. RuntimeError

Correct answer: D. RuntimeError

Adding a key changes the dictionary's size during iteration, and Python raises RuntimeError ('dictionary changed size during iteration'). Iterate over list(d) when you need to modify the dict.

More Coding Interview Problems questions

Exams that ask this topic