Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Default Dict

  • collections
  • defaultdict
counter = {}

word = 'eggplant'

counter[word] += 1
# counter[word] = counter[word] + 1
Traceback (most recent call last):
  File "counter.py", line 5, in <module>
    counter[word] += 1
KeyError: 'eggplant'
counter = {}

word = 'eggplant'

if word not in counter:
    counter[word] = 0
counter[word] += 1

print(counter)
{'eggplant': 1}
from collections import defaultdict

counter = defaultdict(int)

word = 'eggplant'

counter[word] += 1

print(counter)
defaultdict(<class 'int'>, {'eggplant': 1})