import itertools


def _df_multigroupby_aggregate(pv, func=lambda x:x):
    """
    Generate a flattened structure from multigroupby result

    Parameters
    ----------
    pv: dataFrame, dict like structure
    result from :func:`_df_multigroupby`

    func: callable
        reduce the data according to this function (default: identity)

    Returns
    -------
    seq: sequence
        flattened sequence of keys and value
    """
    def aggregate(a, b=()):
        data = []
        for k, v in a:
            if type(v) in (list, tuple,):
                data.append(aggregate(v, b=(k,)))
            else:
                data.append(b + (k, func(v)))
        return data
    return list(itertools.chain(*aggregate(pv)))