17. Using a dictionary to store counts
Like defaultdict, Counter initialize values associated with keys to 0. Note how we get rid of checking to see if a key entry exists?
17.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
17.2. Do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2
3d = defaultdict(int)
4
5for name in names:
6 key = len(name)
7 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))