from typing import Dict
from typing import Any


def unflatten_dict(
        flat_dict: Dict[str, Any],
        separator: str = ' '
    ) -> Dict[str, Any]:
    """
    The inverse operator to flatten_dict.
    Takes a flattened dictionary and returns a nested one.

    :param flat_dict: The dictionary to be nested.
    :param separator: The separator used when flattening the dictionary to separate keys of
        different levels.
    :return: A nested dictionary with structure corresponding to the keys of the flattened
        dictionary passed in.
    """
    # Code adapted from link below.
    # https://www.geeksforgeeks.org/python-convert-flattened-dictionary-into-nested-dictionary
    def split_record(key, value, out):
        """Helper function to split up key."""
        # splitting keys in dict through recursive calls.
        key, *rest = key.split(separator, 1)
        if rest:
            split_record(rest[0], value, out.setdefault(key, {}))
        else:
            out[key] = value

    nested_dict: Dict[str, Any] = {}
    for k, v in flat_dict.items():
        # for each key call split_record which splits keys to form a recursively nested dictionary.
        split_record(k, v, nested_dict)
    return nested_dict