AI Hints
DSA in Python · Lesson 21 of 132

Dictionaries in Practice

Get, Counter, defaultdict.

⏱ 2 min read▶ Video at 24:19🎓 Free
Watch this lesson in the DSA in Python courseWatch on YouTube ↗Full DSA in Python course

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

Dictionaries in Practice
From the video: Dictionaries in Practice
  • 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.

counting.pypython
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))
Output
{'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.

grouping.pypython
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))
Output
{'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)
Next up: Sets — fast membership and unique items