TensorDictBase.keys#
- abstract TensorDictBase.keys(include_nested: bool = False, leaves_only: bool = False, is_leaf: Callable[[Type], bool] | None = None, *, sort: bool = False)#
Returns a view of the keys of the tensordict.
By default, only the top-level keys are returned. A nested key is a tuple of strings, for example
("nested", "b"). See Keys, nested keys, and locking.Warning
The view is lazy. If you modify the tensordict after you call
keys()and before you iterate over the result, the iteration returns the keys after the change.Note
On a
TensorDict, and on most other types,key in td.keys(include_nested=True, leaves_only=True)checks thatkeyexists, not that it is a leaf: it isTruefor a sub-tensordict, although iterating the view does not list it. To test that a key is a leaf, callis_leaf(td.entry_class(key)), withdefault_is_leaf()as the defaultis_leaf. A nested key is never in a view built withinclude_nested=False:("nested", "b") in td.keys()isFalse. On aLazyStackedTensorDict, aTensorDictStoreand aLazyStackedTensorDictStore, it is stillTrue, with aFutureWarning, until TensorDict 0.17.- Parameters:
include_nested (bool, optional) – if
True, the entries of the sub-tensordicts are also returned, with nested keys (tuples of strings). Defaults toFalse.leaves_only (bool, optional) – if
True, only leaves are returned, and sub-tensordicts are skipped. Defaults toFalse.is_leaf (callable, optional) – a function that takes a class and returns
Trueif values of that class count as leaves. It only filters the result whenleaves_only=True. It does not stop the recursion: withinclude_nested=True, a sub-tensordict is still searched even ifis_leafreturnsTruefor it. By default, tensordicts and tensorclasses are not leaves. Seeis_leaf_nontensor()anddefault_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 toFalse.
Examples
>>> from tensordict import TensorDict >>> data = TensorDict({"0": 0, "1": {"2": 2}}, batch_size=[]) >>> list(data.keys()) ['0', '1'] >>> list(data.keys(leaves_only=True)) ['0'] >>> list(data.keys(include_nested=True, leaves_only=True)) ['0', ('1', '2')]
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.