def inv_merge(map, collection=None):
    """
    Invert the dictionary by merging (key, value) pairs with the same values
    into ``value: {key1, key2, ...}`` mappings in the output. Non-repeated
    values are mapped to a single element set.


    Example:
        >>> D = {1: 2, 2: 3, 3: 2}
        >>> inv_merge(D) == {2: {1, 3}, 3: {2}}
        True
    """
    out = {}
    for k, v in map.items():
        if v in out:
            out[v].add(k)
        else:
            out[v] = {k}
    if collection is not None:
        for k, v in out.items():
            out[k] = collection(v)
    return out
