keras/src/tree/optree_impl.py/_sequence_like
def _sequence_like(instance, args):
    # TODO: Support attrs library
    if isinstance(instance, (dict, collections.abc.Mapping)):
        # Pack dictionaries in a deterministic order by sorting the keys.
        # Notice this means that we ignore the original order of `OrderedDict`
        # instances. This is intentional, to avoid potential bugs caused by
        # mixing ordered and plain dicts (e.g., flattening a dict but using a
        # corresponding `OrderedDict` to pack it back).
        result = dict(zip(sorted(instance), args))
        keys_and_values = ((key, result[key]) for key in instance)
        if isinstance(instance, collections.defaultdict):
            # `defaultdict` requires a default factory as the first argument.
            return type(instance)(instance.default_factory, keys_and_values)
        elif isinstance(instance, types.MappingProxyType):
            # MappingProxyType requires a dict to proxy to.
            return type(instance)(dict(keys_and_values))
        else:
            return type(instance)(keys_and_values)
    elif isinstance(instance, collections.abc.MappingView):
        # We can't directly construct mapping views, so we create a list instead
        return list(args)
    elif optree.is_namedtuple(instance):
        instance_type = type(instance)
        try:
            return instance_type(*args)
        except Exception as e:
            raise TypeError(
                f"Couldn't traverse {instance!r} with arguments {args}"
            ) from e
    else:
        # Not a namedtuple
        return type(instance)(args)