How do I serialize pyodbc cursor output (from .fetchone, .fetchmany or .fetchall) as a Python dictionary?
I\'m using bottlepy
Here is a short form version you might be able to use
>>> cursor.select("")
>>> single_row = dict(zip(zip(*cursor.description)[0], cursor.fetchone()))
>>> multiple_rows = [dict(zip(zip(*cursor.description)[0], row)) for row in cursor.fetchall()]
As you might be aware when you add * to a list you basically strips away the list, leaving the individual list entries as parameters to the function you are calling. By using zip we pick the 1st to n entry and zip them together like a the zipper in you pants.
so by using
zip(*[(a,1,2),(b,1,2)])
# interpreted by python as zip((a,1,2),(b,1,2))
you get
[('a', 'b'), (1, 1), (2, 2)]
Since description is a tuple with tuples, where each tuple describes the header and the data type for each column, you can extract the first of each tuple with
>>> columns = zip(*cursor.description)[0]
equivalent to
>>> columns = [column[0] for column in cursor.description]