Counter and defaultdict in Action
Tally items without missing-key errors.
Counter and defaultdict in Action is a free Coding Interview Prep lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Coding Interview Prep learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Tallying Made Easy
Counting how often things appear is everywhere in contests. The collections module gives two tools that make tallying painless. 🧮
The Missing-Key Problem
Plain dicts raise a KeyError when you increment a key that does not exist yet. Special structures remove that friction for you.
Meet Counter
A Counter tallies any iterable in one line, giving each item its frequency as the value. Absent keys simply count as zero.
from collections import Counter
freq = Counter(nums)Read a Count
Index a Counter like a dict, but a missing key returns zero instead of crashing. That makes lookups totally safe.
print(freq[5])
print(freq[999])Most Common Items
Call most_common to get items sorted from highest count down. Pass a number to limit how many top entries you receive.
top3 = freq.most_common(3)Counters Do Math
You can add or subtract two Counters to combine tallies. It merges matching keys and keeps the totals aligned automatically.
total = Counter(a) + Counter(b)Meet defaultdict
A defaultdict supplies a fresh default for any new key, so you never check existence first. You give it the default factory.
from collections import defaultdict
count = defaultdict(int)Increment Without Guards
With defaultdict(int), a missing key starts at zero, so you increment directly. No if-in check clutters your loop.
for v in nums:
count[v] += 1Lists by Default
Use defaultdict(list) when each key collects many values. Appending to a brand-new key just starts a fresh empty list.
groups = defaultdict(list)
groups[key].append(item)Counter or defaultdict
Reach for Counter when you only count items, and defaultdict when each key needs lists, sets, or custom defaults. 🎯
Anagram in One Line
Two words are anagrams exactly when their Counters are equal. The comparison handles every letter frequency at once.
is_anagram = Counter(s) == Counter(t)Quick Check
You want to count occurrences while incrementing missing keys safely.
Recap
Counter tallies items instantly and ranks them, while defaultdict skips missing-key checks for counts, lists, or sets. Both kill boilerplate. 🚀
Frequently asked questions
Is the “Counter and defaultdict in Action” lesson free?
Yes — the full text of “Counter and defaultdict in Action” is free to read here on the web, and the Coding Interview Prep course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Coding Interview Prep course, upgrade to CoddyKit PRO.
What will I learn in “Counter and defaultdict in Action”?
Tally items without missing-key errors. You practise Coding Interview Prep with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Coding Interview Prep?
No prior experience is required. Coding Interview Prep on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Counter and defaultdict in Action” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Coding Interview Prep lesson?
Yes. Every Coding Interview Prep lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Sets for Membership and Dedup
- Dictionaries as Lookup Tables
- Counter and defaultdict in Action
- Group and Bucket with a Map