SyntaxStudy
Sign Up
Python defaultdict & Counter
Python Intermediate 10 min read

defaultdict & Counter

defaultdict & Counter

The collections module provides two dictionary subclasses that handle common counting and grouping tasks elegantly.

defaultdict

from collections import defaultdict

# Groups list items by first letter
words = ["apple", "ant", "banana", "avocado", "berry"]
groups = defaultdict(list)
for word in words:
    groups[word[0]].append(word)
print(dict(groups))
# {'a': ['apple', 'ant', 'avocado'], 'b': ['banana', 'berry']}

Other defaultdict Factories

counter  = defaultdict(int)   # default 0
boolean  = defaultdict(bool)  # default False
nested   = defaultdict(dict)  # default {}

counter["hits"] += 1
counter["hits"] += 1
print(counter["hits"])    # 2
print(counter["misses"])  # 0 (no KeyError)

Counter

from collections import Counter

text = "abracadabra"
c = Counter(text)
print(c)               # Counter({'a': 5, 'b': 2, ...})
print(c.most_common(3)) # top 3
print(c["a"])          # 5

words = "the cat sat on the mat".split()
wc = Counter(words)
print(wc.most_common(2))  # [('the', 2), ...]

# Arithmetic on Counters
c1 = Counter("aab")
c2 = Counter("abb")
print(c1 + c2)   # Counter({'a': 3, 'b': 3})
print(c1 - c2)   # Counter({'a': 1})
Example
from collections import Counter, defaultdict

sentence = "to be or not to be that is the question"
wc = Counter(sentence.split())
print("Top 3 words:", wc.most_common(3))
print("Count of 'to':", wc["to"])

by_len = defaultdict(list)
for w in sentence.split():
    by_len[len(w)].append(w)
print(dict(by_len))
Pro Tip

Counter.most_common() without an argument returns all elements sorted by count — great for generating frequency reports.