Update, delete and what can be a key
After this: Follow an update and a delete, and say why a key must not change.
On this page · 6 sections · 4 checks
You can now insert a pair and look it up. A real hash map can do three more things: change a value, remove a pair, and say whether a key is there. All three build on what you already know.
Start with a small puzzle. put("cat", 3), then put("cat", 5). Is that one entry or two?
put(cat, 3), then put(cat, 5). How many entries does the map hold for cat, and what does get(cat) return?
Update, delete and membership
All three operations start like a lookup: hash the key, go to the slot, and walk the chain comparing keys. They differ only in what happens when the key is found.
Take a slot whose chain holds (cat, 3), then (act, 5).
- Update. Run
put("cat", 9). The key is found, so its value is replaced, and the chain becomes (cat, 9), then (act, 5). Nothing moves, and the count of pairs does not change. If the key had not been found,putwould have added a new pair. So insert and update are one operation in the code. - Delete. Now delete
act. The key is found, so its pair is removed and the chain closes up, leaving only (cat, 9). The count drops by one. The number of slots stays the same, because this table never shrinks. - Membership. This means asking whether a key is in the map, which you write as "cat" in mm.containsKey("cat"). It is a lookup that only reports whether it found the key.
The complete code
This is the whole SimpleHashMap. It joins the pieces from the last three lessons and adds delete, membership and length.
class SimpleHashMap: def __init__(self, capacity=8): self.capacity = capacity self.buckets = [[] for _ in range(capacity)] self.count = 0
def _index(self, key): return sum(ord(ch) for ch in key) % self.capacity
def put(self, key, value): bucket = self.buckets[self._index(key)] for pair in bucket: if pair[0] == key: pair[1] = value # update: same pair, new value return bucket.append([key, value]) self.count += 1 if self.count / self.capacity > 0.75: self._resize()
def get(self, key): bucket = self.buckets[self._index(key)] for stored_key, value in bucket: if stored_key == key: return value return None
def delete(self, key): bucket = self.buckets[self._index(key)] for i, pair in enumerate(bucket): if pair[0] == key: bucket.pop(i) # remove the pair; the chain closes up self.count -= 1 return True return False # nothing to delete
def __contains__(self, key): # enables: "cat" in m return self.get(key) is not None
def __len__(self): # enables: len(m) return self.count
def _resize(self): old_buckets = self.buckets self.capacity *= 2 self.buckets = [[] for _ in range(self.capacity)] self.count = 0 for bucket in old_buckets: for key, value in bucket: self.put(key, value)import java.util.ArrayList;import java.util.List;
public class SimpleHashMap { private static class Pair { String key; int value; Pair(String key, int value) { this.key = key; this.value = value; } }
private int capacity; private List<List<Pair>> buckets; private int count = 0;
public SimpleHashMap() { this(8); }
public SimpleHashMap(int capacity) { this.capacity = capacity; this.buckets = emptyBuckets(capacity); }
private static List<List<Pair>> emptyBuckets(int n) { List<List<Pair>> b = new ArrayList<>(); for (int i = 0; i < n; i++) b.add(new ArrayList<>()); return b; }
private int index(String key) { int sum = 0; for (char ch : key.toCharArray()) sum += ch; return sum % capacity; }
public void put(String key, int value) { List<Pair> bucket = buckets.get(index(key)); for (Pair pair : bucket) { if (pair.key.equals(key)) { pair.value = value; // update: same pair, new value return; } } bucket.add(new Pair(key, value)); count++; if ((double) count / capacity > 0.75) resize(); }
public Integer get(String key) { for (Pair pair : buckets.get(index(key))) { if (pair.key.equals(key)) return pair.value; } return null; }
public boolean remove(String key) { List<Pair> bucket = buckets.get(index(key)); for (int i = 0; i < bucket.size(); i++) { if (bucket.get(i).key.equals(key)) { bucket.remove(i); // remove the pair; the chain closes up count--; return true; } } return false; // nothing to delete }
public boolean containsKey(String key) { return get(key) != null; }
public int size() { return count; }
private void resize() { List<List<Pair>> old = buckets; capacity *= 2; buckets = emptyBuckets(capacity); count = 0; for (List<Pair> bucket : old) { for (Pair pair : bucket) put(pair.key, pair.value); } }}You have already met most of this. Here are the new parts.
- deleteremove is highlighted. It walks the chain and keeps track of the position
i. When it finds the key, it removes the pair at that position, lowerscountby one, and reports success. If the chain ends, it reports that there was nothing to delete. - __contains__containsKey is membership. It calls
getand reports whether a value came back. This simple version treats a stored None as missing. A real dict does not. - __len__size gives the number of pairs.
Watch it happen
This task builds a chain of two pairs, updates one pair and deletes the other. Then it tries to delete a key that is not there, and it looks up the deleted key.
- Insert cat → 3Start by inserting cat.
- Insert act → 5
- Update cat → 9
- Delete act
- Delete tac
- Look up act
- 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
What can be a key
Lookup works because it hashes the key again and arrives at the same slot. So what happens if a key changes after it is stored?
Suppose a key's hash leads to slot 2, and its pair is stored there. Later the key changes, so its hash changes too, and now it leads to slot 5.
- A lookup hashes the changed key and goes to slot 5.
- Slot 5 does not hold the pair, so the answer is "not found".
- The pair is still sitting in slot 2, but no lookup will go there.
So a key must never change while it is in the map. A value that cannot change after it is created is called . Strings and numbers are immutable, and so is a Python tuple of immutable values. A list is not, because you can change it at any time. A value that is safe to use as a key is called .
Python and Java handle this rule differently.
cache = {}cache[("alice", 7)] = "page 7 for alice" # a tuple is immutable: finecache[["alice", 7]] = "page 7 for alice" # TypeError: ... unhashable type: 'list'Map<List<Object>, String> cache = new HashMap<>();List<Object> key = new ArrayList<>(List.of("alice", 7));cache.put(key, "page 7 for alice"); // allowed...key.set(1, 8); // ...but now its hashCode changedcache.get(key); // null: the map looks in the wrong slotCheck yourself
What does this print?
m = SimpleHashMap()m.put("cat", 3)m.put("cat", 5)print(m.get("cat"), len(m))SimpleHashMap m = new SimpleHashMap();m.put("cat", 3);m.put("cat", 5);System.out.println(m.get("cat") + " " + m.size());Which of these can be a key in a Python dict?
Complete deleteremove: the chain walk has found the pair at position i. Which line removes it?
def delete(self, key): bucket = self.buckets[self._index(key)] for i, pair in enumerate(bucket): if pair[0] == key: ________________________ # ← the missing line self.count -= 1 return True return False public boolean remove(String key) { List<Pair> bucket = buckets.get(index(key)); for (int i = 0; i < bucket.size(); i++) { if (bucket.get(i).key.equals(key)) { ________________________ // ← the missing line count--; return true; } } return false; }Connect
The list of operations that a tool offers to your code is called its API. Every operation in this tutorial has a name in the API of your language's hash map. Here they are.
d = {"cat": 3}d["cat"] = 5 # put (update)d.get("ant", 0) # lookup with a default instead of None"cat" in d # membership: Truedel d["cat"] # delete; KeyError if missingd.pop("ant", None) # delete that returns the value, or the defaultd.setdefault("owl", 0) # insert only if the key is missingMap<String, Integer> d = new HashMap<>(Map.of("cat", 3));d.put("cat", 5); // put (update)d.getOrDefault("ant", 0); // lookup with a default instead of nulld.containsKey("cat"); // membership: trued.remove("cat"); // delete; returns the old value or nulld.putIfAbsent("owl", 0); // insert only if the key is missing- Follow an update: find the key in its chain and replace its value.
- Follow a delete: find the key and remove the pair. The table does not shrink.
- Say why a key must not change, and what Python and Java each do about it.
- Match the operations in this tutorial to the names used by dict and HashMap.