Dictionaries & Sets · Question 18 · Hard

New keys are added to a dictionary inside a for loop over the same dictionary. What is the result?

d = {"a": 1, "b": 2}
for k in d:
    d[k.upper()] = 0
print(d)
  1. {'a': 1, 'b': 2, 'A': 0, 'B': 0}
  2. KeyError
  3. {'A': 0, 'B': 0}
  4. RuntimeError
Answer and explanation

Answer: D. RuntimeError

Explanation: A dictionary must not change size while it is being iterated. The first pass adds the key A, and when the loop asks for the next key Python raises RuntimeError: dictionary changed size during iteration. Looping over list(d) avoids this.

Previous: Sets are built from the letters of two words. What is printed? · Next: A keys view is taken before the dictionary is changed. What does this print?

Practise dictionaries & sets

Try a fresh set of dictionaries & sets questions with an explanation after every answer, free and without signing up: Dictionaries & Sets practice. Or sit a full placement mock test.

More dictionaries & sets questions

More python practice

Conditions & Loops · Functions & Scope · Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge