Iterate over a collection and group its values by the provided key
    function. If the key is not callable (a function), then we wrap it in
    templategetter(), so that you can simply do:

    >>> organize([{'foo': 1}, {'foo': 2}, {'foo': 1}], "{foo}")
    {'1': [{'foo': 1}, {'foo': 1}], '2': [{'foo': 2}]}

def organize(data, key):
    """
    Iterate over a collection and group its values by the provided key
    function. If the key is not callable (a function), then we wrap it in
    templategetter(), so that you can simply do:

    >>> organize([{'foo': 1}, {'foo': 2}, {'foo': 1}], "{foo}")
    {'1': [{'foo': 1}, {'foo': 1}], '2': [{'foo': 2}]}
    """
    groups = {}
    if not callable(key):
        key = templategetter(key)
    for row in data:
        k = key(row)
        if groups.has_key(k):
            groups[k].append(row)
        else:
            groups[k] = [row]
    return groups