Looking through [Trac][trac]’s search internals I came across [a chunk where a list of tuples is converted to a list of dictionaries][searchmodule] 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][list], [`zip`][zip] and [`dict`][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.
[trac]: http://trac.edgewall.org
[searchmodule]: http://trac.edgewall.org/browser/tags/trac-0.11.4/trac/search/web_ui.py#L111
[list]: http://docs.python.org/tutorial/datastructures.html#list-comprehensions
[zip]: http://docs.python.org/library/functions.html#zip
[dict]: http://docs.python.org/library/stdtypes.html#typesmapping