zenwalker
6/23/2015 - 3:28 PM

regroup.py

def regroup(data, key, single=False):
    out = {}

    for item in data:
        if callable(key):
            key = key(item)

        if isinstance(item, dict):
            outkey = item[key]
        else:
            outkey = getattr(item, key)

        if not single:
            if outkey not in out:
                out[outkey] = []
            out[outkey].append(item)
        else:
            out[outkey] = item

    return out