def walk_through_dict(
    dictionary, end_fn, max_depth=None, _trace=None, _result=None, **kwargs
):
    """Runs a function at a given level in a nested dictionary.

    If `max_depth` is unspecified, `end_fn()` will be run whenever
    the recursion encounters an object other than a dictionary.

    Parameters
    ----------
    dictionary : foo
        The dictionary to be recursively walked through.
    end_fn : function
        THe function to be run once recursion ends, either at
        `max_depth` or when a non-dictionary is encountered.
    max_depth : int, optional
        How far deep the recursion is allowed to go. By default, the
        recursion is allowed to go as deep as possible (i.e., until
        it encounters something other than a dictionary).
    _trace : tuple, optional
        List of dictionary keys used internally to track nested position.
    _result : dict
        Used internally to pass new dictionaries and avoid changing the
        input dictionary.
    **kwargs : key-value pairs
        Argument values that are passed to `end_fn()`.

    Returns
    -------
    dict
        A processed dictionary. The input dictionary remains unchanged.
    """

    # Define default values
    if max_depth is None:
        max_depth = float("inf")
    if _trace is None:
        _trace = tuple()
    if _result is None:
        _result = dict()

    # If the max_depth is zero, simply run `end_fn()` right away
    if max_depth <= 0:
        return end_fn(dictionary, **kwargs)

    # Iterate over every dictionary key and run `end_fn()` if the value
    # isn't a dictionary and the end depth isn't met. Otherwise, walk
    # through nested dictionary recursively.
    for k, v in dictionary.items():
        # Track nested position
        current_trace = _trace + (k,)
        if isinstance(v, dict) and len(current_trace) < max_depth:
            _result[k] = dict()
            walk_through_dict(v, end_fn, max_depth, current_trace, _result[k], **kwargs)
        else:
            _result[k] = end_fn(v, **kwargs)

    return _result