MySQL: Get column name or alias from query
cursor.description will give you a tuple of tuples where [0] for each is the column header.
num_fields = len(cursor.description)field_names = [i[0] for i in cursor.description]
This is the same as thefreeman but more in pythonic way using list and dictionary comprehension
columns = cursor.description result = [{columns[index][0]:column for index, column in enumerate(value)} for value in cursor.fetchall()]pprint.pprint(result)
Similar to @James answer, a more pythonic way can be:
fields = map(lambda x:x[0], cursor.description)result = [dict(zip(fields,row)) for row in cursor.fetchall()]
You can get a single column with map over the result:
extensions = map(lambda x: x['ext'], result)
or filter results:
filter(lambda x: x['filesize'] > 1024 and x['filesize'] < 4096, result)
or accumulate values for filtered columns:
totalTxtSize = reduce( lambda x,y: x+y, filter(lambda x: x['ext'].lower() == 'txt', result))