TensorDictBase.rename_key#
- TensorDictBase.rename_key_(old_key: NestedKey, new_key: NestedKey, safe: bool = False) Self#
Renames an entry of the tensordict in place and returns the tensordict.
The value is not copied. A locked tensordict raises
RuntimeError(seelock_()). Until TensorDict 0.17, a lockedPersistentTensorDictor store renames the key and warns instead.- Parameters:
old_key (NestedKey) – the key to rename. A missing key raises
KeyError.new_key (NestedKey) – the new key 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 whennew_keyis 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.