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(seelock_()). Until 0.17, a lockedPersistentTensorDictor 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 insideold_key, such as("a", "b")for"a", moves the entry there, astd.set(new_key, td.pop(old_key))does.safe (bool, optional) – if
True, aKeyErroris raised when the new key is already present in the TensorDict, unless it lies insideold_key, which moves with the entry. IfFalse, the existing entry is overwritten. Defaults toFalse.
- 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.