What's the idiomatic Python equivalent to Django's 'regroup' template tag?
Question: <http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup>

I can think of a few ways of doing it with loops but I'd particularly like to
know if there is a neat one-liner.


Answer: Combine
[`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby)
with
[`operator.itemgetter`](http://docs.python.org/library/operator.html#operator.itemgetter)
to get a pretty nice solution:

    
    
    from operator import itemgetter
    from itertools import groupby
    
    key = itemgetter('gender')
    iter = groupby(sorted(people, key=key), key=key)
    
    for gender, people in iter:
        print '===', gender, '==='
        for person in people:
            print person
    

