from typing import Mapping


def _filter_nested_dict(value, key=None, search_terms=None):
    """Return a copy of a nested dictionary where only keys belonging to search_terms are kept."""

    # key is None for the root only.
    # Expression used to test whether we keep a key or not.
    keep = lambda k: k is None or (
        (not search_terms or k in search_terms) and not k.startswith('_'))
    # Process leaves.
    if not isinstance(value, Mapping):
        return value if keep(key) else None
    else:
        dupe_node = {}
        for key, val in value.items():
            cur_node = _filter_nested_dict(val, key=key, search_terms=search_terms)
            if cur_node is not None and (not isinstance(cur_node, dict) or cur_node):
                dupe_node[key] = cur_node
        return dupe_node