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})