Python:使用mysqldb导入一个MySQL表作为字典?

任何人都知道我可以如何使用mysqldb将一个有很多行的MySQL表转换成Python中的字典对象列表?

我的意思是将一列MySQL行,列'a','b'和'c'转换成Python对象,如下所示:

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 } ] 

谢谢 :)

MySQLdb有一个单独的游标类,DictCursor。 您可以将您想要使用的游标类传递给MySQLdb.connect():

 import MySQLdb.cursors MySQLdb.connect(host='...', cursorclass=MySQLdb.cursors.DictCursor) 

如果你需要使用更多的游标,只有一个需要是MySQLdb.cursors.DictCursor,你可以这样做:

 import MySQLdb db = MySQLdb.connect(host='...', db='...', user='...t', passwd='...') list_cursor = db.cursor() dict_cursor = db.cursor(MySQLdb.cursors.DictCursor) 

这是一个古老的post,尽pipe这个答案并不是OP所期望的,但是它的内容大致相同。 它不会生成词典列表,而是生成一个列表字典:

还以为我会提供完整的代码来生成字典:

 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 } 

这产生:

 { 'col1': ['apple','banana'], 'col2':['red','yellow'] }