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)
- {'a': 1, 'b': 2, 'A': 0, 'B': 0}
- KeyError
- {'A': 0, 'B': 0}
- 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
- pop() is called for a key that exists and for one that does not. What does…
- An int, a float and a bool are used as keys in one dictionary literal. What…
- Sets are built from the letters of two words. What is printed?
- A keys view is taken before the dictionary is changed. What does this print?
- A grade dictionary is inverted with a comprehension. What is printed?
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