TheAlgorithms/Python · error · KeyError

{key}

Error message

{key}

What it means

Raised by HashMap.__delitem__ (hash_map.py) with the key as the exception payload: `raise KeyError(key)`. During open-addressing probe iteration, hitting an empty bucket means the key was never inserted, so deletion raises KeyError. (Tombstoned _deleted slots are skipped, not treated as missing.) This is the standard dict-compatible contract — `del hm[k]` behaves like `del d[k]`.

Source

Thrown at data_structures/hashing/hash_map.py:257

        ...     hm[i] = i
        >>> len(hm._buckets)
        100
        >>> hm[75] = 75
        >>> len(hm._buckets)
        200

        ## Resize down
        >>> del hm[75]
        >>> len(hm._buckets)
        200
        >>> del hm[74]
        >>> len(hm._buckets)
        100
        """
        for ind in self._iterate_buckets(key):
            item = self._buckets[ind]
            if item is None:
                raise KeyError(key)
            if item is _deleted:
                continue
            if item.key == key:
                self._buckets[ind] = _deleted
                self._len -= 1
                break
        if self._is_sparse():
            self._size_down()

    def __getitem__(self, key: KEY) -> VAL:
        """
        Returns the item at the given key

        >>> hm = HashMap(5)
        >>> hm._add_item(1, 10)
        >>> hm.__getitem__(1)
        10

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard with membership: `if k in hm: del hm[k]` (HashMap implements __contains__)
  2. Wrap in try/except KeyError for bulk cleanup loops
  3. Canonicalize keys (same type/normalization) at both insert and delete sites

Example fix

# before
del hm[42]  # KeyError if absent

# after
if 42 in hm:
    del hm[42]
Defensive patterns

Strategy: validation

Validate before calling

if key in hm:
    del hm[key]

Try / catch

try:
    del hm[key]
except KeyError:
    pass  # idempotent delete

Prevention

When it happens

Trigger: del hm[k] for a key never added; deleting a key already deleted; deleting after clear(); using a key of a different type than stored (e.g. 1 vs '1', or 1 vs True collisions aside, hash-equal but different keys).

Common situations: Idempotent cleanup code that assumes del is safe; deleting entries filtered from another collection; key-type drift between insert and delete phases.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/93f403e38d8146d7. Report an issue: GitHub.