Populate a dictionary with the result of a query

11,752

Solution 1

Using list comprehension:

things = [{'thing_id': row[0], 'thing_name': row[1]} for row in cursor.fetchall()]

or using list comprehension with zip:

things = [dict(zip(['thing_id', 'thing_name'], row)) for row in cursor.fetchall()]

If you use Cursor.description attribute, you can get column names:

names = [d.name for d in c.description]
things = [dict(zip(names, row)) for row in cursor.fetchall()]

Solution 2

You could use MySQLdb.cursors.DictCursor class instead of MySQLdb.cursors.Cursor by passing cursor class to cursor method:

In [9]: cur = conn.cursor(MySQLdb.cursors.DictCursor)

In [10]: cur.execute('SELECT * FROM test_table')
Out[10]: 3L

In [11]: cur.fetchall()
Out[11]: 
({'create_time': datetime.datetime(2015, 12, 2, 10, 22, 23),
  'id': 1L,
  'name': 'Bob'},
 {'create_time': datetime.datetime(2015, 12, 2, 10, 22, 34),
  'id': 2L,
  'name': 'Stive'},
 {'create_time': datetime.datetime(2015, 12, 2, 10, 22, 37),
  'id': 3L,
  'name': 'Alex'})
Share:
11,752
penitent_tangent
Author by

penitent_tangent

Updated on October 26, 2022

Comments

  • penitent_tangent
    penitent_tangent over 1 year

    I'm currently doing this:

        cursor.execute('SELECT thing_id, thing_name FROM things')
        things = [];
        for row in cursor.fetchall():
            things.append(dict([('thing_id',row[0]),
                                 ('thing_name',row[1])
                                 ]))
    

    Is there some shorthand I can use to do this, or should I write a little helper function?