diff --git a/xarray/core/dataset.py b/xarray/core/dataset.py index 248f516b61b..3c86bd504cf 100644 --- a/xarray/core/dataset.py +++ b/xarray/core/dataset.py @@ -4393,16 +4393,18 @@ def swap_dims( # rename_dims() method that only renames dimensions. dims_dict = either_dict_or_kwargs(dims_dict, dims_kwargs, "swap_dims") - for k, v in dims_dict.items(): - if k not in self.dims: + for current_name, new_name in dims_dict.items(): + if current_name not in self.dims: raise ValueError( - f"cannot swap from dimension {k!r} because it is " + f"cannot swap from dimension {current_name!r} because it is " f"not one of the dimensions of this dataset {tuple(self.dims)}" ) - if v in self.variables and self.variables[v].dims != (k,): + if new_name in self.variables and self.variables[new_name].dims != ( + current_name, + ): raise ValueError( - f"replacement dimension {v!r} is not a 1D " - f"variable along the old dimension {k!r}" + f"replacement dimension {new_name!r} is not a 1D " + f"variable along the old dimension {current_name!r}" ) result_dims = {dims_dict.get(dim, dim) for dim in self.dims} @@ -4412,24 +4414,24 @@ def swap_dims( variables: dict[Hashable, Variable] = {} indexes: dict[Hashable, Index] = {} - for k, v in self.variables.items(): - dims = tuple(dims_dict.get(dim, dim) for dim in v.dims) + for current_name, current_variable in self.variables.items(): + dims = tuple(dims_dict.get(dim, dim) for dim in current_variable.dims) var: Variable - if k in result_dims: - var = v.to_index_variable() + if current_name in result_dims: + var = current_variable.to_index_variable() var.dims = dims - if k in self._indexes: - indexes[k] = self._indexes[k] - variables[k] = var + if current_name in self._indexes: + indexes[current_name] = self._indexes[current_name] + variables[current_name] = var else: index, index_vars = create_default_index_implicit(var) indexes.update({name: index for name in index_vars}) variables.update(index_vars) coord_names.update(index_vars) else: - var = v.to_base_variable() + var = current_variable.to_base_variable() var.dims = dims - variables[k] = var + variables[current_name] = var return self._replace_with_new_dims(variables, coord_names, indexes=indexes)