import random


def select_proportionately(weight_map, total=None):
    """Select from among the keys of the weight map with probability
    proportional to the values. The weight map must be a dictionary with non-
    negative values. The total, if provided, should be the sum of the values in
    the weight map. (This is permitted for efficiency's sake.)"""
    if not isinstance(weight_map, dict):
        raise TypeError(weight_map)
    if not weight_map:
        raise ValueError(weight_map)

    if total is None:
        total = sum(weight_map.values())

    if total < 0:
        raise ValueError(weight_map)
    elif total:
        selector = random.uniform(0, total)
        for candidate, weight in weight_map.items():
            if selector <= weight:
                return candidate
            selector -= weight

    return random.choice(list(weight_map))