Sub topic 3
Counting and grouping with maps
This chapter assumes you can write loops and functions in Python, know what a dictionary and a list are, and have a basic idea of Big-O notation. It covers the two most common jobs for a hash map: counting how often things occur, and grouping items by a shared property.
The working model
A hash map associates a key with a value. Counting and grouping use the same idea. You compute a key from each item, then update the value stored under that key.
- Counting: the value is a number, and you add 1 each time the key appears.
- Grouping: the value is a collection, and you append the item to it.
Each update is a lookup plus a write, which takes constant time on average. Both jobs finish in one pass over the data, so the total cost is O(n) for n items.
Counting occurrences
Suppose you want to count how many times each word appears in a text. The first time you see a word, it has no entry yet. The method dict.get accepts a default that it returns when the key is missing, so a new word starts at 0.
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts) # {'the': 3, 'cat': 1, 'and': 2, 'hat': 1, 'bat': 1}Writing counts[word] += 1 directly would raise KeyError on the first occurrence of each word. The default value avoids that. The next chapter covers missing keys in more detail.
Grouping items by a derived key
Grouping works like counting, except that each value is a list. The key is computed from the item. Here the key is the first letter of each word.
from collections import defaultdict
words = ["apple", "avocado", "banana", "blueberry", "cherry"]
by_letter = defaultdict(list)
for w in words:
by_letter[w[0]].append(w)
print(dict(by_letter))
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}A defaultdict calls the function you give it (here list) to create a value the first time a missing key is used. That removes the "is this key present yet?" check from your loop.
The pattern in general
Both examples follow the same three steps.
- Choose a key function that maps each item to the thing you want to group or count by.
- Look up the current value, using a default when the key is new.
- Update the value and store it back.
The key can be any hashable value, such as a string, a number, or a tuple like (year, month). Choosing the key is the real design decision. Counting words by word.lower() treats "The" and "the" as one entry, while counting by word does not.
| Goal | Value type | Update |
|---|---|---|
| Count occurrences | int | add 1 |
| Group items | list | append the item |
| Collect unique items per key | set | add the item |
| Sum a quantity per key | number | add the amount |
Common errors
- Raising
KeyErrorby reading a key that does not exist yet. Usegetwith a default, or adefaultdict. - Sharing one mutable default between keys. Writing
{k: []}once and reusing the same list for every key puts all items in one list. Create a new list per key, whichdefaultdict(list)does for you. - Reading a
defaultdictby accident. Looking upby_letter["z"]creates an empty entry for"z". Use"z" in by_letterto test without inserting. - Using an unhashable key such as a list. Convert it to a tuple first.
Exercise
You have a list of orders, each a tuple of (customer, amount). Which map type and update would give you the total amount spent per customer in one pass, and what is its time complexity for n orders?
Show answer
Use a map from customer to a number, such as a defaultdict(int) or a dict with get(customer, 0). For each order, add the amount to the value stored under the customer. Each update is O(1) on average, so the whole pass is O(n).