Dictionaries in Practice
Get, Counter, defaultdict.
Now that you know why dictionaries are fast, let's use them well. A few tools make counting and grouping almost effortless.

- Dicts are fast
- Use them well
- Counting and grouping
Counting words
Counting is the most common dictionary job. Get with a default of zero means, if the word isn't there yet, start at zero. The collections module has an even easier tool, Counter, which counts everything in one go. And most common gives the top results. Run it. Both ways agree. The appears three times.
from collections import Counter
text = "the cat sat on the mat the end"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
c = Counter(text.split())
print(c.most_common(2)){'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1, 'end': 1}
[('the', 3), ('cat', 1)]Grouping with defaultdict
Default dict creates a starting value automatically, the first time a key is used. Here, an empty list. That makes grouping easy. We group words by their first letter. Run it.
from collections import defaultdict
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
groups = defaultdict(list)
for w in words:
groups[w[0]].append(w)
print(dict(groups)){'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}Summary
Get with a default, Counter, and default dict make counting and grouping easy, and all of them are O of one per item. Next, sets.
Key takeaways- d.get(k, 0)
- Counter
- defaultdict(list)