One of the most frequently asked questions is how to efficiently get a list of Python dictionaries from a database query rather than the difficult-to-use list of tuples.
1 2 3 4 5 6 7
def toDict(curs): """Convert a DBI result to a list of dictionaries.""" cols = [column for column in curs.description] return [dict(zip(cols, row)) for row in curs.fetchall()] curs.execute('SELECT * FROM mytable') print toDict(curs)
Alternatives to this would be to use an SQL to object mapper such as SQLObject however this recipe will be much faster - although it also does less.