def groupbykey(iterable, key=None):
    """
    Returns a list of sublists of *iterable* grouped by key:
    all elements x of a given sublist have the same
    value key(x).

    key(x) must return a hashable object, such that
    set(key(x) for x in iterable) is possible.

    If not given, key() is the identity funcion.
    """
    if not key:
        key = lambda x: x

    # unique keys
    iterable = list(iterable)
    keys = set(key(x) for x in iterable)

    groups = []
    for k in keys:
        # group with key = k
        groups.append([x for x in iterable if key(x) == k])

    return groups