<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/keras-team/keras/tree/v3.15.1/keras/src/tree/tree_api.py#L337-L396) |

Returns a given flattened sequence packed into a given structure.

    tf.keras.tree.pack_sequence_as(
        structure, flat_sequence
    )

If `structure` is an atom, `flat_sequence` must be a single-item 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. However, instances of
`collections.OrderedDict` are handled differently: their sequence order is
used instead of the sorted keys. The same convention is followed in
`flatten`. This correctly repacks dicts and `OrderedDicts` after they have
been flattened, or vice-versa.

Dictionaries with non-sortable keys are not supported.

#### Examples:

    structure = {"key3": "", "key1": "", "key2": ""}
    flat_sequence = ["value1", "value2", "value3"]
    keras.tree.pack_sequence_as(structure, flat_sequence)
    {"key3": "value3", "key1": "value1", "key2": "value2"}

    structure = (("a", "b"), ("c", "d", "e"), "f")
    flat_sequence = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
    keras.tree.pack_sequence_as(structure, flat_sequence)
    ((1.0, 2.0), (3.0, 4.0, 5.0), 6.0)

    structure = {"key3": {"c": ("alpha", "beta"), "a": ("gamma")},
    "key1": {"e": "val1", "d": "val2"} }
    flat_sequence = ["val2", "val1", 3.0, 1.0, 2.0]
    keras.tree.pack_sequence_as(structure, flat_sequence)
    {'key3': {'c': (1.0, 2.0), 'a': 3.0}, 'key1': {'e': 'val1', 'd': 'val2'} }

    structure = ["a"]
    flat_sequence = [np.array([[1, 2], [3, 4]])]
    keras.tree.pack_sequence_as(structure, flat_sequence)
    [array([[1, 2],
       [3, 4]])]

    structure = ["a"]
    flat_sequence = [keras.ops.ones([2, 2])]
    keras.tree.pack_sequence_as(structure, flat_sequence)
    [array([[1., 1.],
       [1., 1.]]]

<br />

<br />

<br />

| ## Args ||
|---|---|
| `structure` | Arbitrarily nested structure. |
| `flat_sequence` | Flat sequence to pack. |

<br />

<br />

<br />

<br />

| ## Returns ||
|---|---|
| `flat_sequence` converted to have the same recursive structure as `structure`. ||

<br />

<br />

<br />

<br />

| ## Raises ||
|---|---|
| `TypeError` | If `flat_sequence` is not iterable. |
| `ValueError` | If `flat_sequence` cannot be repacked as `structure`; for instance, if `flat_sequence` has too few or too many elements. |

<br />