def aggregate_values_by_key(rdd):
    """Given an RDD in the form of:

        ``RDD[(0, 1), (0, 2), (1, 2)]``

    Aggregate each key (first index in the tuple) into an RDD of 
    keys to lists of all values associated with the key.

    Examples
    --------
    >>> x = sc.parallelize([("a", 1), ("b", 1), ("a", 2)])
    >>> sorted(aggregate_values_by_key(x).collect())
    [('a', [1, 2]), ('b', [1])]

    Parameters
    ----------
    rdd : RDD
        The RDD in the form of ``RDD[(0, 1), (0, 2), (1, 2)]``.
    """
    def to_list(a):
        return [a]

    def append(a, b):
        a.append(b)
        return a

    def extend(a, b):
        a.extend(b)
        return a

    # group by (using aggregate) the key to get a list of values
    return rdd.map(lambda r: (r[0], r[1]))\
              .combineByKey(to_list, append, extend)