I would like to get the result of the fetchall operation in a list instead of tuple of tuple or tuple of dictionaries. For example,
cursor = connection.cursor() #Cursor could be a normal cursor or dict cursor query = "Select id from bs" cursor.execute(query) row = cursor.fetchall()
Now, the problem is the resultant row is either ((123,),(234,)) or ({'id':123}, {'id':234}) What I am looking for is (123,234) or [123,234]. Be best if I can save on parsing the resulset. Thanks in advance
And what about list comprehensions? If result is ((123,), (234,), (345,))
:
>>> row = [item[0] for item in cursor.fetchall()] >>> row [123, 234, 345]
If result is ({'id': 123}, {'id': 234}, {'id': 345})
:
>>> row = [item['id'] for item in cursor.fetchall()] >>> row [123, 234, 345]
I'm sure that after all this time, you've solved this problem, however, for some people who may not know how to get the values of a cursor as a dictionary using MySQLdb, you can use this method found here:
import MySQLdb as mdb con = mdb.connect('localhost', 'testuser', 'test623', 'testdb') with con: cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT * FROM Writers LIMIT 4") rows = cur.fetchall() for row in rows: print row["Id"], row["Name"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With