TensorDictBase.to_dict#
- TensorDictBase.to_dict(*, retain_none: bool = True, convert_tensors: bool | Literal['numpy'] = False, tolist_first: bool = False) dict[str, Any]#
Returns a nested dictionary with the entries of the tensordict.
Nested tensordicts and tensorclasses become nested dicts. The tensors are not copied unless
convert_tensorsis set. Non-tensor data is returned as its Python value.- Keyword Arguments:
retain_none (bool, optional) – if
True, theNonefields of tensorclasses are written in the dict asNone. IfFalse, they are dropped. Defaults toTrue.convert_tensors (bool or str, optional) – if
True, tensors are converted to (nested) Python lists withtorch.Tensor.tolist(). If"numpy", they are converted to NumPy arrays. IfFalse, they are kept as tensors. Defaults toFalse.tolist_first (bool, optional) – if
True, a nested tensordict is converted withtolist(), so that a nested tensordict with batch dimensions becomes a list of dicts, one per element. Defaults toFalse.
- Returns:
A dict whose keys are those of the tensordict.
- Raises:
RuntimeError – on a lazy stack whose tensordicts have different keys (see Variable-size data).
See also
tolist(),numpy()andfrom_dict(), which converts back.Examples
>>> import torch >>> from tensordict import TensorDict >>> >>> td = TensorDict( ... a=torch.arange(6).view(2, 3), ... b=TensorDict(c=torch.arange(4).reshape(2, 2), batch_size=(2, 2)), ... batch_size=(2,) ... ) >>> print(td.to_dict()) {'a': tensor([[0, 1, 2], [3, 4, 5]]), 'b': {'c': tensor([[0, 1], [2, 3]])}} >>> print(td.to_dict(convert_tensors=True)) {'a': [[0, 1, 2], [3, 4, 5]], 'b': {'c': [[0, 1], [2, 3]]}}
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.