Counter & defaultdict
Published by Brayan K
Counter and defaultdict are specialized dictionaries from the collections module: Counter tallies how often each item appears in one line, while defaultdict auto-creates a starting value for new keys so grouping and counting need no boilerplate checks.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Count elements, not the representation you happen to see
An iterable supplies the units being counted. Passing one string counts characters; passing a list of words counts words. A Counter keeps one entry per distinct hashable element and stores its count. Choose the units before asking for the most common result.
from collections import Counter
text = "tea tea"
letters = Counter(text)
words = Counter(text.split())
print(sorted(letters.items()))
print(words.most_common())
# ✅ Expected output:
# [(' ', 1), ('a', 2), ('e', 2), ('t', 2)]
# [('tea', 2)]The space is an element of the original string too. Splitting it changes the input units; it is not something Counter does automatically. Case and punctuation are also kept unless you deliberately normalize them. For general mapping behavior, see Dictionaries in Python.
from collections import Counter
stock = Counter(tea=2)
print(stock["coffee"])
print("coffee" in stock)
stock["coffee"] = 0
print("coffee" in stock)
print(list(stock.items()))
# ✅ Expected output:
# 0
# False
# True
# [('tea', 2), ('coffee', 0)]A missing Counter key reads as zero without being inserted. Explicitly setting a count to zero retains a key, so membership asks whether the key is stored, not whether stock is positive. Use stock[item] > 0 for availability. To remove a stored zero entry, delete its key; to keep only positive counts, make +stock.
Updates add counts; subtraction has two different meanings
from collections import Counter
tally = Counter(tea=2, coffee=1)
tally.update(["tea", "tea"])
tally.update({"coffee": 3})
print(sorted(tally.items()))
print(tally.total())
# ✅ Expected output:
# [('coffee', 4), ('tea', 4)]
# 8Counter.update adds incoming counts. The mapping form means “add this many,” whereas an iterable supplies individual observations. Plain dict.update overwrites values; importing that expectation into Counter would lose track of what the tally means.
from collections import Counter
stock = Counter(tea=2, coffee=1)
sold = Counter(tea=3, coffee=1)
balance = stock.copy()
balance.subtract(sold)
print(sorted(balance.items()))
print(sorted((stock - sold).items()))
print(sorted((+balance).items()))
# ✅ Expected output:
# [('coffee', 0), ('tea', -1)]
# []
# []subtract mutates the counter and retains zero or negative balances. The binary - operation creates a multiset-style result and drops nonpositive counts. That makes subtraction useful for remaining items but unsuitable for reporting shortages. Addition, intersection & and union | also produce only positive counts; intersection takes the per-key minimum and union takes the maximum, rather than summing.
from collections import Counter
left = Counter(tea=3, coffee=1)
right = Counter(tea=1, coffee=2)
print(sorted((left + right).items()))
print(sorted((left & right).items()))
print(sorted((left | right).items()))
# ✅ Expected output:
# [('coffee', 3), ('tea', 4)]
# [('coffee', 1), ('tea', 1)]
# [('coffee', 2), ('tea', 3)]Most-common ties and elements follow precise rules
from collections import Counter
votes = Counter(["blue", "red", "red", "blue", "green"])
print(votes.most_common(2))
counts = Counter(tea=2, coffee=0, cocoa=-1)
print(list(counts.elements()))
print(counts.total())
# ✅ Expected output:
# [('blue', 2), ('red', 2)]
# ['tea', 'tea']
# 1most_common orders by descending count; tied elements keep first-encounter order. If you require alphabetical tie-breaking, choose that policy explicitly using Sorting with sorted() & key. elements() repeats each element according to its positive integer count, ignoring zero and negatives. total() sums all counts, including negatives; it is not the length of elements() when deficits exist.
Counters can hold noninteger values, but not every operation has a useful meaning for them: elements() needs integer repetition counts. Counts are data you maintain, not values the class automatically constrains to nonnegative integers.
A defaultdict factory is called only for a missing bracket lookup
from collections import defaultdict
groups = defaultdict(list)
for category, item in [("drink", "tea"), ("food", "rice"), ("drink", "coffee")]:
groups[category].append(item)
print(dict(groups))
print(groups["drink"] is groups["food"])
# ✅ Expected output:
# {'drink': ['tea', 'coffee'], 'food': ['rice']}
# FalsePass list, the callable factory, so each missing key gets a fresh list. Do not pass list(), which is an already-created list. The factory is called with no arguments; it cannot infer the key from a parameter. If the value must depend on the key, use an explicit branch or a deliberate mapping subclass.
from collections import defaultdict
groups = defaultdict(list())
# ✅ Expected error:
# TypeError: first argument must be callable or Nonefrom collections import defaultdict
groups = defaultdict(list)
print(groups.get("drink"))
print("drink" in groups)
print(groups["drink"])
print("drink" in groups)
# ✅ Expected output:
# None
# False
# []
# TrueOnly missing-key bracket lookup triggers this factory. get and membership testing do not create a group. A typo inside brackets can silently add an empty entry, so use a non-inserting probe when reading optional data. This differs from Counter, which returns zero for missing keys without storing them.
from collections import defaultdict
counts = defaultdict(int)
for status in ["open", "closed", "open"]:
counts[status] += 1
print(dict(counts))
# ✅ Expected output:
# {'open': 2, 'closed': 1}int() supplies zero, then the increment stores the new count. Counter is usually more direct for an existing iterable of observations; defaultdict is useful when values are built up during a more involved loop. Dictionary Methods Deep Dive compares setdefault, including evaluation of unused defaults.
Complete a grouping step and a shortage calculation
Group names by team using a factory that creates fresh lists. Then subtract sales while retaining a negative balance, so a shortage remains visible instead of disappearing.
from collections import Counter, defaultdict
teams = defaultdict(___)
for team, name in [("red", "Asha"), ("blue", "Bea"), ("red", "Chen")]:
teams[team].append(name)
stock = Counter(tea=2)
stock.___(Counter(tea=3))
print(dict(teams))
print(stock["tea"])
# 👉 replace ___ with list
# 👉 replace ___ with subtract
# ✅ Expected output:
# {'red': ['Asha', 'Chen'], 'blue': ['Bea']}
# -1Prepare a stock report that does not hide deficits
Start with stock tea: 2 and coffee: 1. Process orders A/tea, B/tea, C/tea and D/coffee. Build a Counter of demand and a defaultdict of customer names per drink. Print each drink in alphabetical order with its demand, remaining balance, and customer names. Keep a zero balance and a negative balance in the report; do not silently discard them. The task deliberately groups and counts the same observations for different purposes.
from collections import Counter, defaultdict
stock = Counter(tea=2, coffee=1)
orders = [("A", "tea"), ("B", "tea"), ("C", "tea"), ("D", "coffee")]
demand = Counter()
customers = defaultdict(list)
for customer, drink in orders:
demand[drink] += 1
customers[drink].append(customer)
balance = stock.copy()
balance.subtract(demand)
for drink in sorted(demand):
print(drink, demand[drink], balance[drink], customers[drink])
# ✅ Expected output:
# coffee 1 0 ['D']
# tea 3 -1 ['A', 'B', 'C']The original stock remains available because the subtraction modifies a copy. This model assumes one unit per order and string drink names; variable quantities would need a different input contract. The collections reference documents the Counter arithmetic and defaultdict missing-key behavior used here.
Practice quiz
What does this program print? from collections import Counter c = Counter(tea=2) print(c["coffee"], "coffee" in c)
- 0 True
- None False
- 0 False
- KeyError
Answer: 0 False. A missing Counter lookup returns zero but does not store the key.
What does this program print? from collections import Counter c = Counter(a=2) c.update({"a": 3}) print(c["a"])
- 3
- 5
- 2
- 1
Answer: 5. Counter.update adds counts, unlike dict.update replacement.
What does this program print? from collections import Counter a = Counter(x=1) b = Counter(x=2) c = a.copy() c.subtract(b) print(c["x"], dict(a - b))
- -1 {'x': -1}
- 0 {}
- 1 {'x': 1}
- -1 {}
Answer: -1 {}. subtract retains the negative balance; binary subtraction removes nonpositive entries.
What does this program print? from collections import Counter c = Counter(["b", "a", "a", "b"]) print(c.most_common(1))
- [('b', 2)]
- [('a', 2)]
- [('b', 1)]
- [('a', 1)]
Answer: [('b', 2)]. Tied counts retain first-encounter order, so b precedes a.
What does this program print? from collections import defaultdict d = defaultdict(list) print(d.get("x")) print("x" in d)
- [] True
- None False
- [] False
- None True
Answer: None False. get does not call the missing-key factory or insert a key.
Which expression supplies a fresh empty list for each missing group?
- defaultdict(list())
- defaultdict([])
- dict.fromkeys(keys, [])
- defaultdict(list)
Answer: defaultdict(list). The callable list creates a new object each time; an existing list is not a callable factory.
What does this program print? from collections import Counter c = Counter(a=2, b=0, c=-1) print(list(c.elements())) print(c.total())
- ['a', 'a'] 1
- ['a', 'a'] 2
- ['a', 'a', 'c'] 1
- ['a'] 1
Answer: ['a', 'a'] 1. elements repeats positive integer counts only; total includes the negative count.
What does this program print? from collections import Counter a = Counter(x=3) b = Counter(x=2) print((a + b)["x"], (a | b)["x"], (a & b)["x"])
- 5 5 2
- 3 5 2
- 5 3 2
- 5 2 3
Answer: 5 3 2. Addition sums, union takes the maximum, and intersection takes the minimum.
Continue this course
- Previous: Dictionary Methods Deep Dive
- Next: deque & Queues — O(1) appends and pops at both ends with collections.deque
- Quick reference: Python cheat sheet › Standard Library