Python: use mysqldb to import a MySQL table as a dictionary?

匿名 (未验证) 提交于 2019-12-03 01:17:01

问题:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!