Skip to content
Tuples to dicts, toot sweet!

Tuples to dicts, toot sweet!

June 19, 2009

Looking through Trac’s search internals I came across a chunk where a list of tuples is converted to a list of dictionaries for the convenience of the template engine. Each tuple has five fields: href, title, date, author and excerpt.

for idx, result in enumerate(results):
    results[idx] = {'href': result[0], 'title': result[1],
                    'date': format_datetime(result[2]),
                    'author': result[3], 'excerpt': result[4]}

This allows the template author to use nice names for the fields in a row, like ${result.href} etc. Looking at this reminded me of another approach that uses list comprehension, zip and dict.

keys = ('href', 'title', 'date', 'author', 'excerpt')
results = [dict(zip(keys, row)) for row in results]
for row in results:
    row['date'] = format_datetime(row['date'])

The second line in this snippet is where the list of dictionaries is created, but one still has to go back and format the datetime values (the third and fourth lines). There’s no advantage in speed (the majority of the execution time is spent in format_datetime) but I like it a little better.

Maybe if Trac used the second approach I would like Trac a little better too.

Last updated on