ActiveState Code

Recipe 528939: Converting DBI results to a list of dictionaries


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.

Python
1
2
3
4
5
6
7
def toDict(curs):
    """Convert a DBI result to a list of dictionaries."""
    cols = [column[0] for column in curs.description]
    return [dict(zip(cols, row)) for row in curs.fetchall()]

curs.execute('SELECT * FROM mytable')
print toDict(curs)

Discussion

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.

Comments

  1. 1. At 9:26 a.m. on 18 sep 2007, thanos vassilakis said:

    Otherwise if you have DictCursor.. cursor = conn.cursor (MySQLdb.cursors.DictCursor)

Sign in to comment