5. Using a dictionary to store counts
Like defaultdict, Counter initializes missing counts to zero. That lets you avoid checking whether a key already exists.
Counter captures a common problem domain directly and gives you additional operations such as most-common queries for free. Using the dedicated type reduces bookkeeping and makes the intent obvious to readers.
5.1. Don’t do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2
3d = {}
4for name in names:
5 key = len(name)
6 if key not in d:
7 d[key] = 0
8 d[key] = d[key] + 1
5.2. Do this
1from collections import defaultdict
2
3names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
4
5d = defaultdict(int)
6
7for name in names:
8 key = len(name)
9 d[key] = d[key] + 1
1from collections import Counter
2
3names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
4
5d = Counter()
6for name in names:
7 key = len(name)
8 d[key] = d[key] + 1
1from collections import Counter
2
3names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
4
5d = Counter(map(lambda s: len(s), names))