import _typing


def sort_dict(a_dict: dict, key: _typing.Callable = None, reverse: bool = False) -> dict:
    """Return a copy of a dictionary, sorted by its keys. Nested / recursive.

    :param a_dict: dictionary
    :param key: optional function to use for sorting, default `None`. Example: `len` for string keys.
    :param reverse: False: sort ascending, True: descending.
    :return: sorted copy of dictionary
    """
    return {k: sort_dict(v) if isinstance(v, dict) else v for k, v in sorted(a_dict.items(), key=key, reverse=reverse)}