Rate this Page
★ ★ ★ ★ ★

TensorDictBase.setdefault#

TensorDictBase.setdefault(key: NestedKey, default: Tensor | TensorCollection | Any, inplace: bool = False) → Tensor | TensorCollection#

Returns the entry at key, after writing default there if the key is missing.

As for dict.setdefault(), an existing entry is not changed. The result is read with get(), so a non-tensor entry returns its NonTensorData.

Parameters:
  • key (NestedKey) – the key of the entry.

  • default (Tensor, TensorDictBase or any object) – the value written if the key is missing.

  • inplace (bool, optional) – passed to set() when default is written. Defaults to False.

Raises:

RuntimeError – if the key is missing and the tensordict is locked, or if the leading dimensions of default do not match the batch size.

Examples

>>> import torch
>>> from tensordict import TensorDict
>>> td = TensorDict({}, batch_size=[3])
>>> td.setdefault("a", torch.zeros(3))
tensor([0., 0., 0.])
>>> td.setdefault("a", torch.ones(3))  # "a" exists: not changed
tensor([0., 0., 0.])

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

Tutorials that use setdefault#

Getting, setting, and nesting keys

Getting, setting, and nesting keys