from typing import Dict
from typing import Any


def get_contexts_for_widgets(response) -> Dict[str, Dict[str, Any]]:
    """
    Searches through the response's context for subcontexts of widgets,
    and returns a dictionary with the widgets' `id` attribute as key
    and the widget's context dictionary as value.
    """
    widget_contexts = {}
    for subcontext in response.context:
        if "widget" not in subcontext:
            continue

        for subcontext_dict in subcontext:
            if type(subcontext_dict) is not dict or "widget" not in subcontext_dict:
                continue

            widget = subcontext_dict["widget"]
            widget_id = widget["attrs"]["id"]
            widget_contexts[widget_id] = subcontext_dict

    return widget_contexts