| | 243 | By default, the Python DB API will return results without their field names, |
| | 244 | which means you end up with a ``list`` of values, rather than a ``dict``. At a |
| | 245 | small cost of performance, you can apply field names to the results by using |
| | 246 | something like this:: |
| | 247 | |
| | 248 | def dictfetchall(cursor): |
| | 249 | "Returns all rows from a cursor as a dict" |
| | 250 | desc = cursor.description |
| | 251 | return [ |
| | 252 | dict(zip([col[0] for col in desc], row)) |
| | 253 | for row in cursor.fetchall() |
| | 254 | ] |
| | 255 | |
| | 256 | Here is an example of the difference between the two:: |
| | 257 | |
| | 258 | >>> cursor.execute("SELECT id, parent_id from test LIMIT 2"); |
| | 259 | >>> cursor.fetchall() |
| | 260 | ((54360982L, None), (54360880L, None)) |
| | 261 | |
| | 262 | >>> cursor.execute("SELECT id, parent_id from test LIMIT 2"); |
| | 263 | >>> dictfetchall(cursor) |
| | 264 | [{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}] |
| | 265 | |
| | 266 | |