问题
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?
回答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()]
回答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'})
来源:https://stackoverflow.com/questions/34034943/populate-a-dictionary-with-the-result-of-a-query