def _get_stack_index(
        self,
        dim,
        multi=False,
        create_index=False,
    ) -> tuple[Index | None, dict[Hashable, Variable]]:
        """Used by stack and unstack to get one pandas (multi-)index among
        the indexed coordinates along dimension `dim`.

        If exactly one index is found, return it with its corresponding
        coordinate variables(s), otherwise return None and an empty dict.

        If `create_index=True`, create a new index if none is found or raise
        an error if multiple indexes are found.

        """
        stack_index: Index | None = None
        stack_coords: dict[Hashable, Variable] = {}

        for name, index in self._indexes.items():
            var = self._variables[name]
            if (
                var.ndim == 1
                and var.dims[0] == dim
                and (
                    # stack: must be a single coordinate index
                    (not multi and not self.xindexes.is_multi(name))
                    # unstack: must be an index that implements .unstack
                    or (multi and type(index).unstack is not Index.unstack)
                )
            ):
                if stack_index is not None and index is not stack_index:
                    # more than one index found, stop
                    if create_index:
                        raise ValueError(
                            f"cannot stack dimension {dim!r} with `create_index=True` "
                            "and with more than one index found along that dimension"
                        )
                    return None, {}
                stack_index = index
                stack_coords[name] = var

        if create_index and stack_index is None:
            if dim in self._variables:
                var = self._variables[dim]
            else:
                _, _, var = _get_virtual_variable(self._variables, dim, self.sizes)
            # dummy index (only `stack_coords` will be used to construct the multi-index)
            stack_index = PandasIndex([0], dim)
            stack_coords = {dim: var}

        return stack_index, stack_coords
Used by stack and unstack to get one pandas (multi-)index among
        the indexed coordinates along dimension `dim`.

        If exactly one index is found, return it with its corresponding
        coordinate variables(s), otherwise return None and an empty dict.

        If `create_index=True`, create a new index if none is found or raise
        an error if multiple indexes are found.

        
xarray/core/dataset.py