- collections
- defaultdict
Default Dict
examples/dictionary/counter.py
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'
examples/dictionary/counter_condition.py
counter = {} word = 'eggplant' if word not in counter: counter[word] = 0 counter[word] += 1 print(counter)
{'eggplant': 1}
examples/dictionary/default_dict.py
from collections import defaultdict counter = defaultdict(int) word = 'eggplant' counter[word] += 1 print(counter)
defaultdict(<class 'int'>, {'eggplant': 1})