from typing import List
from typing import Dict
import torch


def reduce_list_of_dicts(data: List[Dict[str, torch.Tensor]], mode="average", divisor=None) -> Dict[str, torch.Tensor]:
    """Average a list of dictionary mapping keys to Tensors.

    Parameters
    ----------
    data: List[Dict[str, torch.Tensor]])
    mode: str
        Which reduction mode, average reduces the dictionary, sum just adds while average computes the average.
    divisor: None or int
        If given values are divided by this factor.

    Returns
    -------
    Dict[str, torch.Tensor]: Reduced dictionary.
    """
    if not data:
        return {}

    if mode not in ["average", "sum"]:
        raise ValueError("Reduction can only be `sum` or `average`.")

    if not divisor:
        divisor = 1.0

    result_dict = {k: torch.zeros_like(v) for k, v in data[0].items()}

    for elem in data:
        result_dict = {k: result_dict[k] + v for k, v in elem.items()}

    if mode == "average":
        divisor *= len(data)

    return {k: v / divisor for k, v in result_dict.items()}