def normalize(dist):
    """Scale values in a dictionary or list such that they represent
    a probability distribution.  Each value lies in 0 <= value <= 1
    and the sum of all values is 1.

    :param dist:  The distribution.  May be numeric, or a dictionary of numeric
                  values.  Note that dictionaries are modified, other iterables
                  have copies returned.

    :return val: Returns a dictionary or list.
    """
    if isinstance(dist, dict):
        total = sum(dist.values())
        for key in dist:
            dist[key] = dist[key] / total
            assert 0 <= dist[key] <= 1  # probabilities must be between 0 and 1
        return dist
    total = sum(dist)
    return [(n / total) for n in dist]