{"record":{"id":"f553d6465b45bbaa","repo":"pola-rs/polars","slug":"key","errorCode":null,"errorMessage":"{key}","messagePattern":"\\{key\\}","errorType":"exception","errorClass":null,"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/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/datatypes/classes.py#L828-L864","documentation":"Indexing a Categories object with a string looks up the category by name; if the name is not present, a plain KeyError with the key as its message is raised. This is standard mapping-style behavior for missing keys.","triggerScenarios":"categories['nonexistent_string'] where the string is not a registered category; typos in category names; querying a Categories instance from a different namespace/table than the data.","commonSituations":"Looking up a category that was filtered out or dropped; case-sensitivity mistakes ('A' vs 'a'); cross-dataset category reuse.","solutions":["Check membership first with `key in categories`","Wrap the lookup in try/except KeyError","Verify you are using the Categories instance that actually backs your column"],"exampleFix":"// before\ncat = categories['setosa ']\n// after\ncat = categories['setosa'] if 'setosa' in categories else None","handlingStrategy":"validation","validationCode":"if key not in categories:\n    key = key.strip()  # or handle missing before lookup\ncat = categories[key]","typeGuard":"def has_category(categories, key: str) -> bool:\n    return isinstance(key, str) and key in categories","tryCatchPattern":"try:\n    cat = categories[name]\nexcept KeyError:\n    cat = None  # or log and skip","preventionTips":["Check `in` membership before string lookups","Normalize/trim category strings consistently","Ensure you use the Categories instance from the same dataset/namespace"],"tags":["polars","categorical","keyerror","lookup"],"backgroundTag":"resource-not-found","analyzedSha":"fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e","analyzedAt":"2026-09-18T22:14:11.667Z","contentChangedAt":"2026-09-18T22:14:11.667Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}