Python collections Counter, defaultdict and deque
What you will learn
Counter: counting thingsdefaultdict: dictionaries that create missing valuesdeque: fast queues, rotation andmaxlen- A look at
namedtuple,OrderedDictandChainMap - Choosing the right container
1. The collections module
Lists, tuples, dictionaries and sets cover most needs, but a few jobs come up so often that Python provides ready-made containers in the collections module. They are subclasses or relatives of the built-in types, so they feel familiar:
from collections import Counter, defaultdict, deque
2. Counter
A Counter is a dictionary specialised for counting: it maps each item to how many times it occurs.
c = Counter("mississippi")
print(c)
print(c["s"], c["z"])
print(c.most_common(2))
print(sum(c.values()), len(c))
Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
4 0
[('i', 4), ('s', 4)]
11 4
Counter(iterable)counts the items (the letters of the string here).- A missing item gives 0 instead of a
KeyError. most_common(n)lists thenmost frequent items as(item, count)pairs, highest first (ties keep the order of first appearance).sum(c.values())is the total number counted;len(c)the number of different items.c.total()also gives the total.
Count words:
words = "the cat and the hat and the bat".split()
print(Counter(words).most_common(3))
[('the', 3), ('and', 2), ('cat', 1)]
Update counts later with update (adds) and subtract:
c2 = Counter(a=3, b=1)
c2.update("aab")
print(c2)
c2.subtract({"a": 1})
print(c2)
Counter({'a': 5, 'b': 2})
Counter({'a': 4, 'b': 2})
Counters support arithmetic, which acts on the counts:
x, y = Counter("aab"), Counter("abc")
print(x + y)
print(x - y)
print(x & y)
print(x | y)
Counter({'a': 3, 'b': 2, 'c': 1})
Counter({'a': 1})
Counter({'a': 1, 'b': 1})
Counter({'a': 2, 'b': 1, 'c': 1})
+ adds counts, - subtracts and drops zero or negative results, & keeps the smaller count, | keeps the larger. Counters can even hold negative counts if set directly; unary + removes them. Remember this compact way of counting from loops (lesson 9.3):
# instead of: counts[w] = counts.get(w, 0) + 1
counts = Counter(words)
Quick check: what is `Counter("hello")["l"]`, and `Counter("hello")["z"]`?
2 and 0.
3. defaultdict
In a normal dictionary, reading a missing key raises KeyError. A defaultdict is given a factory function; when a key is missing it calls the factory to create a value, stores it and returns it:
d = defaultdict(list)
for k, v in [("a", 1), ("b", 2), ("a", 3)]:
d[k].append(v)
print(d)
print(dict(d))
defaultdict(<class 'list'>, {'a': [1, 3], 'b': [2]})
{'a': [1, 3], 'b': [2]}
No if k not in d: d[k] = [] is needed. This is the classic way to group items (lesson 9.6). Other factories:
dd = defaultdict(int)
for ch in "hello":
dd[ch] += 1
print(dict(dd))
print(defaultdict(lambda: "n/a")["x"])
print(defaultdict(set)["s"])
nested = defaultdict(lambda: defaultdict(int))
nested["x"]["y"] += 1
print({k: dict(v) for k, v in nested.items()})
{'h': 1, 'e': 1, 'l': 2, 'o': 1}
n/a
set()
{'x': {'y': 1}}
int()gives0,list()gives[],set()gives an empty set, and any function without arguments works (lambda: "n/a").- Reading a missing key creates it. This is convenient but can surprise you:
d = defaultdict(list)
d["zzz"]
print(dict(d), "zzz" in d)
{'zzz': []} True
If you only want to look without creating, use d.get("zzz") or "zzz" in d. Convert to a plain dict(d) when you are done adding.
4. deque
A list is quick at its end (append, pop) but slow at the front: list.pop(0) shifts every other item (lesson 7.7). A deque ("double-ended queue", pronounced "deck") is fast at both ends:
dq = deque([1, 2, 3])
dq.append(4)
dq.appendleft(0)
print(dq)
print(dq.pop(), dq.popleft(), dq, len(dq), dq[1])
deque([0, 1, 2, 3, 4])
4 0 deque([1, 2, 3]) 3 2
append/popwork at the right end;appendleft/popleftat the left.- It still has
len, indexing and iteration (indexing in the middle is slower than for a list). - Removing from an empty deque raises
IndexError: pop from an empty deque.
Other methods: rotate(n) shifts the items cyclically, extend and extendleft add many:
dq.rotate(1)
print(dq)
dq.extend([9])
dq.extendleft([7, 8])
print(dq)
deque([3, 1, 2])
deque([8, 7, 3, 1, 2, 9])
(extendleft adds one item at a time at the left, so [7, 8] ends up reversed as 8, 7.)
maxlen: a sliding window
Give a deque a maxlen and it keeps only the newest items; older ones fall off the other end:
m = deque(maxlen=3)
for i in range(6):
m.append(i)
print(m, m.maxlen)
last = deque(["l1", "l2", "l3", "l4", "l5"], maxlen=3)
print(list(last))
deque([3, 4, 5], maxlen=3) 3
['l3', 'l4', 'l5']
That makes "the last N things" easy: recent searches, the last lines of a file (lesson 15.1), a moving average:
def moving_avg(xs, n):
window = deque(maxlen=n)
for x in xs:
window.append(x)
yield sum(window) / len(window)
print(list(moving_avg([1, 2, 3, 4, 5, 6], 3)))
[1.0, 1.5, 2.0, 3.0, 4.0, 5.0]
Speed
For queues (first in, first out; lesson 7.6), a deque is the right tool. A quick timing on the check computer (removing 2,000 items from the front of a 100,000-item container) found deque.popleft() faster than list.pop(0); the exact times vary, but the gap grows with size.
5. A look at three more
namedtuple(lesson 8.4): tuples with named fields.OrderedDict: a dictionary with extra order-related tools such asmove_to_end. Since plain dictionaries keep insertion order (lesson 9.5), you rarely need it.
from collections import OrderedDict
od = OrderedDict(a=1, b=2)
od.move_to_end("a")
print(od, list(od))
OrderedDict({'b': 2, 'a': 1}) ['b', 'a']
ChainMap: looks through several dictionaries in order, without merging them. Handy for layered settings (command line, then config file, then defaults):
from collections import ChainMap
cm = ChainMap({"a": 1}, {"a": 2, "b": 3})
print(cm["a"], cm["b"], dict(cm))
1 3 {'a': 1, 'b': 3}
6. Choosing
| Need | Use |
|---|---|
| count occurrences, find the most common | Counter |
| group items by a key | defaultdict(list) or defaultdict(set) |
| a queue or a "last N" window | deque (with maxlen for a window) |
| a record with named fields | namedtuple or a dataclass (lesson 13.11) |
| layered lookups | ChainMap |
| anything else | the built-in list, dict, set, tuple |
Worked example: analysing a short text
Count the words, group them by first letter, keep the "recently used" words (most recent last, no duplicates, at most three), and find the most common pair of neighbouring words.
from collections import Counter, defaultdict, deque
text = """The cat sat on the mat. The dog sat on the log.
A cat and a dog met on the mat."""
words = [w.strip(".,").lower() for w in text.split()]
freq = Counter(words)
print(freq.most_common(4))
print(freq["cat"], freq["bird"])
by_letter = defaultdict(set)
for w in words:
by_letter[w[0]].add(w)
for letter in sorted(by_letter)[:3]:
print(letter, sorted(by_letter[letter]))
recent = deque(maxlen=3)
for word in ["cat", "dog", "mat", "log", "cat"]:
if word in recent:
recent.remove(word)
recent.append(word)
print(list(recent))
pairs = Counter(zip(words, words[1:]))
print(pairs.most_common(2))
[('the', 5), ('on', 3), ('cat', 2), ('sat', 2)]
2 0
a ['a', 'and']
c ['cat']
d ['dog']
['cat']
['cat', 'dog']
['cat', 'dog', 'mat']
['dog', 'mat', 'log']
['mat', 'log', 'cat']
[(('on', 'the'), 3), (('sat', 'on'), 2)]
| Part | Idea |
|---|---|
Counter(words) |
counts; a missing word gives 0 (no KeyError) |
defaultdict(set) |
words grouped by first letter, without duplicates |
deque(maxlen=3) |
the oldest recent word drops out automatically; remove then append moves a repeated word to the end |
zip(words, words[1:]) |
neighbouring pairs; a Counter counts the pairs (tuples are hashable, lesson 9.7) |
The sentences are made up.
Common mistakes
- Counting with a plain dictionary and
KeyErrorwhenCounterdoes it. - Reading a
defaultdictkey to test it, creating it by accident. - Using
list.pop(0)for a queue in a loop with lots of data. - Forgetting
maxlenand letting a deque grow without limit. - Expecting
Countersubtraction to keep negatives (usesubtract). - Indexing the middle of a huge deque (slow); a list is better for random access.
- Printing a
defaultdictand forgetting it shows its factory; usedict(d).
Key takeaways
Countercounts items, returns0for missing ones, and offersmost_common,update,subtractand arithmetic.defaultdict(factory)creates missing values automatically: ideal for grouping and counting.dequeis fast at both ends;maxlenmakes a sliding window of the latest items.OrderedDict,ChainMapandnamedtuplecover special jobs.- Prefer the built-in containers unless one of these fits the job exactly.
Practice
1. Count the letters in "banana" and show the most common one.
Show answer
Counter("banana").most_common(1) # [('a', 3)]
2. Group the words of a list by their length.
Show answer
groups = defaultdict(list)
for w in words:
groups[len(w)].append(w)
3. What does deque(maxlen=5) do when a sixth item is appended?
Show answer
The oldest item (at the opposite end) is dropped, so only the five newest remain.
4. Why is deque.popleft() better than list.pop(0) for a long queue?
Show answer
list.pop(0) shifts every remaining item, which gets slower as the list grows; popleft is fast regardless of size.
5. What is the result of Counter("aab") - Counter("abc")?
Show answer
Counter({'a': 1}). Subtraction keeps only positive counts.
6. How can you test for a key in a defaultdict without creating it?
Show answer
Use key in d or d.get(key). Indexing with d[key] creates the key.