donnemartin/interactive-coding-challenges · error · KeyError
Key not found
Error message
Key not found
What it means
Raised by HashMap.get when the key is not present in the bucket its hash maps to. This open hashing (chaining) implementation returns the value only on an exact item.key match; otherwise the miss escalates to KeyError rather than returning None.
Source
Thrown at arrays_strings/hash_map/hash_map_solution.ipynb:149
" self.table = [[] for _ in range(self.size)]\n",
"\n",
" def _hash_function(self, key):\n",
" return key % self.size\n",
"\n",
" def set(self, key, value):\n",
" hash_index = self._hash_function(key)\n",
" for item in self.table[hash_index]:\n",
" if item.key == key:\n",
" item.value = value\n",
" return\n",
" self.table[hash_index].append(Item(key, value))\n",
"\n",
" def get(self, key):\n",
" hash_index = self._hash_function(key)\n",
" for item in self.table[hash_index]:\n",
" if item.key == key:\n",
" return item.value\n",
" raise KeyError('Key not found')\n",
"\n",
" def remove(self, key):\n",
" hash_index = self._hash_function(key)\n",
" for index, item in enumerate(self.table[hash_index]):\n",
" if item.key == key:\n",
" del self.table[hash_index][index]\n",
" return\n",
" raise KeyError('Key not found')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{View on GitHub (pinned to 358f2cc604)
Solutions
- Check the key with in-style logic or catch KeyError instead of assuming a None default
- Use a wrapper that returns a default: return map.get(k) if present else default
- Verify the key was actually set (logging set/remove calls) before reading
Example fix
# before
value = hmap.get(key) # raises KeyError on miss
# after
try:
value = hmap.get(key)
except KeyError:
value = 'default' Defensive patterns
Strategy: try-catch
Validate before calling
try:
value = hmap.get(key)
except KeyError:
value = None Type guard
def key_exists(hmap, key) -> bool:
try:
hmap.get(key)
return True
except KeyError:
return False Try / catch
try:
value = hmap.get(key)
except KeyError:
value = default_value Prevention
- Do not assume dict.get-style None defaults; this map raises
- Wrap access with a default-returning helper
When it happens
Trigger: Calling get on a removed or never-set key; getting a key whose hash bucket was searched without a match (collision chains included).
Common situations: Assuming a default return value like dict.get; typos or case mismatches in keys; reading after concurrent/logical removal.
Related errors
AI-assisted analysis of donnemartin/interactive-coding-challenges@358f2cc604 (2026-08-28).
Data as JSON: /api/errors/535861fab0a6ec54.
Report an issue: GitHub.