Rate this Page
★ ★ ★ ★ ★

TensorDictBase.items#

TensorDictBase.items(include_nested: bool = False, leaves_only: bool = False, is_leaf=None, *, sort: bool = False) → Iterator[tuple[str, Tensor | TensorCollection]]#

Returns a generator of the (key, value) pairs of the tensordict.

By default, only the top-level entries are returned, and a sub-tensordict is returned as one value. See Keys, nested keys, and locking for nested keys and leaves.

Parameters:
  • include_nested (bool, optional) – if True, the entries of the sub-tensordicts are also returned, with nested keys (tuples of strings). Defaults to False.

  • leaves_only (bool, optional) – if True, only leaves are returned, and sub-tensordicts are skipped. Defaults to False.

  • is_leaf (callable, optional) – a function that takes a class and returns True if values of that class count as leaves. It only filters the result when leaves_only=True. It does not stop the recursion: with include_nested=True, a sub-tensordict is still searched even if is_leaf returns True for it. By default, tensordicts and tensorclasses are not leaves. See is_leaf_nontensor() and default_is_leaf().

Keyword Arguments:

sort (bool, optional) – if True, the keys are sorted. Nested keys are sorted by their joined name: ("a", "key") sorts as "a.key". Sorting takes extra time on large tensordicts. Defaults to False.

Examples

>>> import torch
>>> from tensordict import TensorDict
>>> td = TensorDict(
...     a=torch.zeros(2),
...     nested=TensorDict(b=torch.ones(2, 3), batch_size=[2]),
...     batch_size=[2],
... )
>>> for key, value in td.items(include_nested=True, leaves_only=True):
...     print(key, value.shape)
a torch.Size([2])
('nested', 'b') torch.Size([2, 3])

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

Tutorials that use items#

Functional calls and ensembles with TensorDict

Functional calls and ensembles with TensorDict

Getting, setting, and nesting keys

Getting, setting, and nesting keys