{"record":{"id":"f553d6465b45bbaa","repo":"pola-rs/polars","slug":"key","errorCode":null,"errorMessage":"{key}","messagePattern":"\\{key\\}","errorType":"exception","errorClass":"KeyError","httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/datatypes/classes.py","lineNumber":846,"sourceCode":"        phys = self._categories.physical()\n        if phys == \"u8\":\n            return pldt.UInt8\n        elif phys == \"u16\":\n            return pldt.UInt16\n        elif phys == \"u32\":\n            return pldt.UInt32\n        else:\n            msg = \"unknown physical dtype\"\n            raise RuntimeError(msg)\n\n    def is_global(self) -> bool:\n        \"\"\"Returns whether this refers to the global categories.\"\"\"\n        return self._categories.is_global()\n\n    def __getitem__(self, key: str | int) -> str | int:\n        if isinstance(key, str):\n            if (cat := self._categories.get_cat(key)) is None:\n                raise KeyError(key)\n            return cat\n        elif isinstance(key, int):\n            if (s := self._categories.cat_to_str(key)) is None:\n                msg = f\"category index out of range: {key}\"\n                raise IndexError(msg)\n            return s\n        else:\n            msg = f\"invalid key type {type(key)}; expected str or int\"\n            raise TypeError(msg)\n\n    def __contains__(self, item: str | int) -> bool:\n        if isinstance(item, str):\n            return self._categories.get_cat(item) is not None\n        elif isinstance(item, int):\n            return self._categories.cat_to_str(item) is not None\n        else:\n            return False\n","sourceCodeStart":828,"sourceCodeEnd":864,"githubUrl":"https://github.com/pola-rs/polars/blob/68506541d2de983056c9eb244e1ea05fab377dfc/py-polars/src/polars/datatypes/classes.py#L828-L864","documentation":"KeyError raised by a Categorical's CategoriesMapping.__getitem__ when a string key is not present among the category values. Polars categories form a fixed string-to-code mapping, so looking up an unseen string cannot return a code and the raw key is re-raised as the KeyError payload.","triggerScenarios":"Accessing categories_mapping['missing'] (or the mapping object returned by a Categorical dtype's categories) with a string that was never registered as a category, e.g. after filtering or on a categorical built from a different vocabulary.","commonSituations":"Comparing vocabularies across two categorical columns; interactive inspection of category mappings after slice/filter operations; typos in category lookups.","solutions":["Check membership first: 'key' in mapping (the class defines __contains__)","Use mapping.get_cat(key) which returns None instead of raising","Recode or build the union of categories (cat.union, Categorical full/lexical ordering setup) before cross-column lookups"],"exampleFix":"# before\ncode = dtype.categories['unknown_label']\n# after\ncode = dtype.categories.get_cat('unknown_label')\nif code is None:\n    ...  # handle missing category","handlingStrategy":"validation","validationCode":"if dtype.categories.get_cat(name) is None:\n    raise KeyError(f'{name} not a category')","typeGuard":"def is_category(dtype: pl.DataType, name: str) -> bool:\n    cats = getattr(getattr(dtype, 'categories', None), '_categories', None)\n    return cats is not None and cats.get_cat(name) is not None","tryCatchPattern":"try:\n    code = dtype.categories[name]\nexcept KeyError:\n    code = None  # unseen category","preventionTips":["Prefer get_cat()/in checks over direct indexing","Unify category vocabularies before cross-column operations","Watch for filter/slice narrowing the category set"],"tags":["python","polars","categorical","key-error","categories"],"backgroundTag":"categorical-key-missing","analyzedSha":"68506541d2de983056c9eb244e1ea05fab377dfc","analyzedAt":"2026-08-28T18:02:35.179Z","contentChangedAt":"2026-08-28T18:02:35.179Z","schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}