可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Anyone know how I can use mysqldb to turn a MySQL table, with lots of rows, into a list of dictionary objects in Python?
I mean turning a set of MySQL rows, with columns 'a', 'b', and 'c', into a Python object that that looks like this:
data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]
Thanks :)
回答1:
MySQLdb has a separate cursor class for this, the DictCursor. You can pass the cursor class you want to use to MySQLdb.connect():
import MySQLdb.cursors MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor)
回答2:
If you need to use more cursors and only one needs to be MySQLdb.cursors.DictCursor you can do:
import MySQLdb db = MySQLdb.connect(host='...', db='...', user='...t', passwd='...') list_cursor = db.cursor() dict_cursor = db.cursor(MySQLdb.cursors.DictCursor)
回答3:
This is an ancient post, and while this answer isn't exactly what the OP was looking for, it is much along the same lines. Instead of generating a list of dictionaries, it generates a dictionary of lists:
Also thought I'd provide the full code for generating the dictionary:
import MySQLdb import MySQLdb.cursors dict_serv = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'mypassword', cursorclass = MySQLdb.cursors.DictCursor) with dict_serv as c: c.execute("USE mydb") c.execute("SELECT col1, col2 FROM mytable WHERE id = 'X123'") # Save the dictionary to a separate variable init_dict = c.fetchall() # This line builds the column headers sql_cols = [ col[0] for col in c.description ] # This is a list comprehension within a dictionary comprehension # which builds the full dictionary in a single line. sql_dict = { k : [ d[k] for d in init_dict ] for k in sql_cols }
Which yields:
{ 'col1': ['apple','banana'], 'col2':['red','yellow'] }