import itertools
import operator


def invert_otm_mapping(mapping):
    """Inverts a one-to-many mapping."""

    # Create a list of inverted (v, k) tuples.
    tuples = (itertools.zip_longest(v, [k], fillvalue=k)
              for k, v in mapping.items() if len(v) > 0) # yapf: disable
    tuples = itertools.chain.from_iterable(tuples)

    # Sort tuples by first element.
    id_attr = operator.itemgetter(0)
    sorted_tuples = sorted(tuples, key=id_attr)

    # Create inverted dictionary using groupby.
    inverted = {k: set(list(zip(*grp))[1])
                for k, grp in itertools.groupby(
                    sorted_tuples, key=id_attr)}

    return inverted