Rate this Page
★ ★ ★ ★ ★

TensorDictBase.rename_key#

TensorDictBase.rename_key_(old_key: NestedKey, new_key: NestedKey, safe: bool = False) → Self#

Renames a key with a new string and returns the same tensordict with the updated key name.

The value is not copied. A locked tensordict raises RuntimeError (see lock_()). Until 0.17, a locked PersistentTensorDict or store renames the key and warns instead.

Parameters:
  • old_key (NestedKey) – key to be renamed. A missing key raises KeyError.

  • new_key (NestedKey) – new name of the entry. An empty key raises KeyError. A key inside old_key, such as ("a", "b") for "a", moves the entry there, as td.set(new_key, td.pop(old_key)) does.

  • safe (bool, optional) – if True, a KeyError is raised when the new key is already present in the TensorDict, unless it lies inside old_key, which moves with the entry. If False, the existing entry is overwritten. Defaults to False.

Returns:

self

Examples

>>> import torch
>>> from tensordict import TensorDict
>>> td = TensorDict({"a": torch.zeros(3), "b": {"c": torch.ones(3)}}, [3])
>>> td = td.rename_key_("a", "x")
>>> td = td.rename_key_(("b", "c"), ("b", "y"))
>>> list(td.keys(include_nested=True, leaves_only=True))
[('b', 'y'), 'x']

Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.

Tutorials that use rename_key_#

Getting, setting, and nesting keys

Getting, setting, and nesting keys