Which fix removes the bug?
from collections import defaultdict
counts = defaultdict(int, {'a': 1, 'b': 2})
if counts['zz'] > 0:
print('zz seen')
print(len(counts)) # expected 2
- Compare with
counts['zz'] >= 1 - Use
defaultdict(list, ...) - Wrap it in
try/except KeyError - Read with
counts.get('zz', 0)
Indexing a defaultdict with a missing key inserts it with the default, so just reading counts['zz'] adds a third key. get() reads without inserting.
Play Problem Solving ▸