Skip to content


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

[1.3.X] Fixed #16293: Document a way to return dicts with column name…

…s from a DB cursor. Backport of [16808] from trunk.

git-svn-id: bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit f242c02fb97254715cf929d011851e4469d1fcfe 1 parent 0326e2e
James Bennett ubernostrum authored
Showing with 24 additions and 0 deletions.
  1. +24 −0 docs/topics/db/sql.txt
24 docs/topics/db/sql.txt
@@ -236,6 +236,30 @@ alias::
# Your code here...
+By default, the Python DB API will return results without their field
+names, which means you end up with a ``list`` of values, rather than a
+``dict``. At a small performance cost, you can return results as a
+``dict`` by using something like this::
+ def dictfetchall(cursor):
+ "Returns all rows from a cursor as a dict"
+ desc = cursor.description
+ return [
+ dict(zip([col[0] for col in desc], row))
+ for row in cursor.fetchall()
+ ]
+Here is an example of the difference between the two::
+ >>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
+ >>> cursor.fetchall()
+ ((54360982L, None), (54360880L, None))
+ >>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
+ >>> dictfetchall(cursor)
+ [{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]
.. _transactions-and-raw-sql:
Transactions and raw SQL
Please sign in to comment.
Something went wrong with that request. Please try again.