{"record":{"id":"eb63ed325abdf609","repo":"pola-rs/polars","slug":"cannot-select-elements-using-key-of-type-qualifie","errorCode":null,"errorMessage":"cannot select elements using key of type {qualified_type_name(key)!r}: {key!r}","messagePattern":"cannot select elements using key of type (.+?): (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"py-polars/src/polars/_utils/getitem.py","lineNumber":90,"sourceCode":"        try:\n            indices = pl.Series(\"\", key, dtype=Int64)\n        except TypeError:\n            msg = f\"cannot select elements using Sequence with elements of type {qualified_type_name(first)!r}\"\n            raise TypeError(msg) from None\n\n        indices = _convert_series_to_indices(indices, s.len())\n        return _select_elements_by_index(s, indices)\n\n    elif isinstance(key, pl.Series):\n        indices = _convert_series_to_indices(key, s.len())\n        return _select_elements_by_index(s, indices)\n\n    elif _check_for_numpy(key) and isinstance(key, np.ndarray):\n        indices = _convert_np_ndarray_to_indices(key, s.len())\n        return _select_elements_by_index(s, indices)\n\n    msg = f\"cannot select elements using key of type {qualified_type_name(key)!r}: {key!r}\"\n    raise TypeError(msg)\n\n\ndef _select_elements_by_slice(s: Series, key: slice) -> Series:\n    return PolarsSlice(s).apply(key)  # type: ignore[return-value]\n\n\ndef _select_elements_by_index(s: Series, key: Series) -> Series:\n    return s._from_pyseries(s._s.gather_with_series(key._s))\n\n\n# `str` overlaps with `Sequence[str]`\n# We can ignore this but we must keep this overload ordering\n@overload\ndef get_df_item_by_key(\n    df: DataFrame, key: tuple[SingleIndexSelector, SingleColSelector]\n) -> Any: ...\n\n","sourceCodeStart":72,"sourceCodeEnd":108,"githubUrl":"https://github.com/pola-rs/polars/blob/fe841f959ef4d2ceefc05a310d33ed7b1ab24e5e/py-polars/src/polars/_utils/getitem.py#L72-L108","documentation":"This is the fallback raise at the end of get_series_item_by_key: the key given to Series.__getitem__ matched none of the supported kinds (int, slice, bool mask, Sequence of ints, pl.Series of indices/mask, numpy 1-D int/bool array). Polars raises TypeError naming the key's type and repr so the caller can see exactly what was unsupported.","triggerScenarios":"s[{'a': 1}]; s[frozenset({0, 1})]; s[some_generator]; s[None]; s[np 2-D array] (handled by ndarray path only if convertible); any custom object passed as Series index.","commonSituations":"Passing a dict mapping from pandas-style label lookup; forgetting to convert a generator or set to a list; passing a 2-D numpy array of indices; passing None after an upstream function returned an optional key.","solutions":["Convert the key to an int list or numpy int array before indexing: s[list(key)].","Wrap the key in pl.Series(indices, dtype=Int64) if it is an iterable of ints.","For boolean selection, pass a pl.Series or numpy bool array, not a set/dict.","Check for None keys and use a default (e.g. slice(None)) before indexing.","Use s.gather(indices) or s.filter(mask) as explicit alternatives."],"exampleFix":"// before\ns[{0, 2}]\n// after\ns[list({0, 2})]","handlingStrategy":"type-guard","validationCode":"def valid_series_key(key):\n    return (isinstance(key, (int, slice)) or\n            (hasattr(key, 'dtype') and hasattr(key, 'to_list')) or\n            (isinstance(key, (list, tuple)) and all(isinstance(x, int) for x in key)) or\n            (type(key).__module__ == 'numpy' and getattr(key, 'ndim', 2) == 1))\nassert valid_series_key(k), f'unsupported Series key: {type(k)}'","typeGuard":"def is_selectable_key(key: object) -> bool:\n    import numpy as np\n    import polars as pl\n    return (isinstance(key, (int, slice))\n            or isinstance(key, (pl.Series, list, tuple))\n            or isinstance(key, np.ndarray) and key.ndim <= 1)","tryCatchPattern":"try:\n    out = series[key]\nexcept TypeError as e:\n    if 'cannot select elements using key' in str(e):\n        out = series[list(key)] if hasattr(key, '__iter__') else series[0]\n    else:\n        raise","preventionTips":["Materialize generators/sets/dicts into lists before indexing.","Guard against None keys returned by optional-lookup helpers.","Flatten numpy arrays to 1-D before use as indices.","Prefer explicit gather/filter over generic __getitem__ for dynamic keys."],"tags":["polars","series","indexing","unsupported-key"],"backgroundTag":"invalid-argument-value","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"}