Welcome, guest | Sign In | My Account | Store | Cart

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, 7 lines
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)

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.

1 comment

thanos vassilakis 14 years, 2 months ago  # | flag

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

Created by Andrew Smith on Sun, 9 Sep 2007 (PSF)
Python recipes (4591)
Andrew Smith's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks