Hash maps in practice
After this: Write the counting, grouping, finding-repeats and caching patterns.
On this page · 6 sections · 4 checks
You now know how a hash map works inside. This lesson is about using one. Most everyday uses follow one of four patterns. A is a way of solving a kind of problem that comes up again and again.
We start with a job that shows why a hash map helps: count how often each word appears in the sentence "the cat saw the dog". First, try it with a plain list of pairs.
words = "the cat saw the dog".split()counts = [] # a list of [word, count] pairsfor word in words: for pair in counts: # scan every pair, every time if pair[0] == word: pair[1] += 1 break else: counts.append([word, 1])String[] words = "the cat saw the dog".split(" ");List<Object[]> counts = new ArrayList<>(); // a list of {word, count} pairsfor (String word : words) { boolean found = false; for (Object[] pair : counts) { // scan every pair, every time if (pair[0].equals(word)) { pair[1] = (int) pair[1] + 1; found = true; break; } } if (!found) counts.add(new Object[] {word, 1});}The outer loop takes one word at a time. The inner loop looks through the pairs so far. If it finds the word, it adds one to that word's count. If it does not, the code adds a new pair with the count 1.
So every word causes a search through all the pairs seen so far. For one sentence this does not matter. For a whole book, it is the slow linear search that this tutorial started with, repeated for every word. The four patterns below replace that kind of search with a hash map.
1 · Counting
Here is the same sentence with a hash map. The keys are the words, and the values are their counts.
theis not in the map, so store (the, 1).catis not in the map, so store (cat, 1).sawis not in the map, so store (saw, 1).theis in the map with count 1, so store (the, 2).dogis not in the map, so store (dog, 1).
The rule is the same for every word: look it up, using 0 if it is missing, add one, and store it back.
words = "the cat saw the dog".split()counts = {}for word in words: counts[word] = counts.get(word, 0) + 1 # lookup with default, then putprint(counts["the"])
from collections import Counterprint(Counter(words)["the"]) # the library version2 2
String[] words = "the cat saw the dog".split(" ");Map<String, Integer> counts = new HashMap<>();for (String word : words) { counts.put(word, counts.getOrDefault(word, 0) + 1); // lookup with default, then put}System.out.println(counts.get("the"));
for (String word : words) counts.merge(word, 1, Integer::sum); // the library versionSystem.out.println(counts.get("the")); // 4 now: merged on top of the first count2 4
counts.get(word, 0)counts.getOrDefault(word, 0) gives the word's count, or 0 if the word is new. Each language also has a shorter way, shown after the loop: Countermerge does the whole job in one call.does the lookup and the store for one word in one call, inside a loop. The Java program runs its second count on the same map, so the reaches 4 there.
The visualizer runs the same sentence through the table. The first time a word appears is an insert, and every later time is an update.
- Insert the → 1The first word is not in the map yet, so insert it with count 1.
- Insert cat → 1
- Insert saw → 1
- Update the → 2
- Insert dog → 1
- 0—
- 1—
- 2—
- 3—
- 4—
- 5—
- 6—
- 7—
Start with the first task above, or try any key.
- count
- 0
- load
- 0.00
- compares
- 0
2 · Grouping
Grouping means sorting items into piles. Take the words apple, avocado, banana, blueberry and cherry, and group them by first letter. The key is the letter, and the value is a list of words.
| Key | Value |
|---|---|
| a | apple, avocado |
| b | banana, blueberry |
| c | cherry |
There is one thing to handle. The first time a key appears, it has no list yet, so the list must be created.
words = ["apple", "avocado", "banana", "blueberry", "cherry"]groups = {}for word in words: groups.setdefault(word[0], []).append(word) # the list for this key, created if missingprint(groups["a"])
from collections import defaultdictgroups = defaultdict(list) # the library versionfor word in words: groups[word[0]].append(word)['apple', 'avocado']
List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry");Map<Character, List<String>> groups = new HashMap<>();for (String word : words) { groups.computeIfAbsent(word.charAt(0), k -> new ArrayList<>()).add(word); // created if missing}System.out.println(groups.get('a'));[apple, avocado]
setdefaultcomputeIfAbsent gives you the list stored under the key. If the key is missing, it first creates an empty list and stores it. Either way you get a list, and the word is then added to it.
3 · Finding repeats with a seen set
Sometimes the only question is: have I seen this before? The values are not needed. A is a hash map without the values: it stores only keys. Here it finds the first repeat in the numbers 4, 1, 7, 1, 9.
- 4 is not in the set, so add it.
- 1 is not in the set, so add it.
- 7 is not in the set, so add it.
- 1 is in the set, so the first repeat is 1.
def first_repeat(stream): seen = set() for item in stream: if item in seen: # membership: a lookup with no value return item seen.add(item) return None
print(first_repeat([4, 1, 7, 1, 9]))1
static Integer firstRepeat(int[] stream) { Set<Integer> seen = new HashSet<>(); for (int item : stream) { if (seen.contains(item)) { // membership: a lookup with no value return item; } seen.add(item); } return null;}
System.out.println(firstRepeat(new int[] {4, 1, 7, 1, 9}));1
The same idea removes duplicates from a list: keep an item only if it is not in the set yet.
4 · Caching
A keeps answers you have already worked out. If a function is called again with the same input, it looks the answer up and does not work it out again. The key is the input, and the value is the answer. For a function, this is also called memoization.
Our example is the Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, and so on, where each number is the sum of the two before it. A function fib that calls itself twice would work out the same small answers again and again. A cache stops that.
cache = {}
def fib(n): if n < 2: return n if n in cache: # seen this input before? return the stored answer return cache[n] cache[n] = fib(n - 1) + fib(n - 2) return cache[n]
from functools import lru_cache # the library version
@lru_cache(maxsize=None)def fib2(n): return n if n < 2 else fib2(n - 1) + fib2(n - 2)static Map<Integer, Long> cache = new HashMap<>();
static long fib(int n) { if (n < 2) return n; if (cache.containsKey(n)) { // seen this input before? return the stored answer return cache.get(n); } long result = fib(n - 1) + fib(n - 2); cache.put(n, result); return result;}After the two smallest cases, fib checks whether n is in the cache. If it is, the stored answer is returned straight away. If it is not, the function works out the answer, stores it, and returns it. Python also has a ready-made version, lru_cache, shown at the end.The cache is a map from the input n to the answer.
Check yourself
What does this print?
counts = {}for ch in "banana": counts[ch] = counts.get(ch, 0) + 1print(counts["a"], len(counts))Map<Character, Integer> counts = new HashMap<>();for (char ch : "banana".toCharArray()) { counts.put(ch, counts.getOrDefault(ch, 0) + 1);}System.out.println(counts.get('a') + " " + counts.size());What does this print?
groups = {}for n in [3, 8, 5, 12, 7]: groups.setdefault(n % 2, []).append(n)print(groups[1])Map<Integer, List<Integer>> groups = new HashMap<>();for (int n : new int[] {3, 8, 5, 12, 7}) { groups.computeIfAbsent(n % 2, k -> new ArrayList<>()).add(n);}System.out.println(groups.get(1));You have a long list of numbers and must decide whether any number appears twice. Which pattern fits?
Complete the grouping code: add word to the list stored under key, and create the list if the key is new.
words = ["apple", "avocado", "banana", "blueberry", "cherry"]groups = {}for word in words: key = word[0] ________________________________________ # ← add word to the list for key, creating it if neededprint(groups["b"])List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry");Map<Character, List<String>> groups = new HashMap<>();for (String word : words) { char key = word.charAt(0); ________________________________________ // ← add word to the list for key, creating it if needed}System.out.println(groups.get('b'));Connect
- Write the counting pattern, by hand and with the standard library.
- Write the grouping pattern, by hand and with the standard library.
- Use a set to find repeats and remove duplicates.
- Cache a function's results with a map, and name the library version.