What is the correct fix?
counts = {"a": 1, "b": 0}
for k in counts:
if counts[k] == 0:
del counts[k]
- Iterate a copy:
for k in list(counts) - Iterate a copy:
for k in dict(counts[k]) - Change
del counts[k]tocounts.pop() - Change the test to
if not counts[k]:
Deleting while iterating a dict raises RuntimeError; iterate over a snapshot of the keys.
Play Problem Solving ▸