Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the idiomatic Python equivalent to Django's 'regroup' template tag?

Tags:

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.

like image 681
Andy Baker Avatar asked Jan 25 '09 15:01

Andy Baker


People also ask

What is with tag in Django template?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. In the next chapters you will learn about the most common template tags.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What is a Django tag?

Django Template Tags are simple Python functions which accepts a 1 or more value, an optional argument, process those values and return a value to be displayed on the page. First, In your application folder, create a "templatetags" directory at the same level as the models and views.

What does the built in Django template tag spaceless do?

spaceless. Removes whitespace between HTML tags. This includes tab characters and newlines.


2 Answers

Combine itertools.groupby with 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
like image 105
Jouni K. Seppänen Avatar answered Oct 20 '22 07:10

Jouni K. Seppänen


If the source of data (people in this case) is already sorted by the key, you can bypass the sorted call:

iter = groupby(people, key=lambda x:x['gender'])
for gender, people in iter:
    print '===', gender, '==='
    for person in people:
        print person

Note: If sorted is a common dictionary, there are no guarantees of order; therefore you must call sorted. Here I'm supposing that sorted is a collections.OrderedDict or some other kind of ordered data structure.

like image 20
Euribates Avatar answered Oct 20 '22 07:10

Euribates