ML Community Day is November 9! Join us for updates from TensorFlow, JAX, and more Learn more


Returns a given flattened sequence packed into a given structure.

Used in the notebooks

Used in the tutorials

If structure is a scalar, flat_sequence must be a single-element list; in this case the return value is flat_sequence[0].

If structure is or contains a dict instance, the keys will be sorted to pack the flat sequence in deterministic order. This is true also for OrderedDict instances: their sequence order is ignored, the sorting order of keys is used instead. The same convention is followed in flatten. This correctly repacks dicts and OrderedDicts after they have been flattened, and also allows flattening an OrderedDict and then repacking it back using a corresponding plain dict, or vice-versa. Dictionaries with non-sortable keys cannot be flattened.


  1. Python dict:
  structure = { "key3": "", "key1": "", "key2": "" }
  flat_sequence = ["value1", "value2", "value3"]
  tf.nest.pack_sequence_as(structure, flat_sequence)
    {'key3': 'value3', 'key1': 'value1', 'key2': 'value2'}
  1. For a nested python tuple:
  structure = (('a','b'), ('c','d','e'), 'f')
  flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
  tf.nest.pack_sequence_as(structure, flat_sequence)
    ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0)
  1. For a nested dictionary of dictionaries:
  structure = { "key3": {"c": ('alpha', 'beta'), "a": ('gamma')},
                "key1": {"e": "val1", "d": "val2"} }
  flat_sequence = ['val2', 'val1', 3.0, 1.0, 2.0]
  tf.nest.pack_sequence_as(structure, flat_sequence)
    {'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'} }
  1. Numpy array (considered a scalar):
  structure = ['a']
  flat_sequence = [np.array([[1, 2], [3, 4]])]