Output pyodbc cursor results as python dictionary

后端 未结 8 1621
孤独总比滥情好
孤独总比滥情好 2020-11-29 18:37

How do I serialize pyodbc cursor output (from .fetchone, .fetchmany or .fetchall) as a Python dictionary?

I\'m using bottlepy

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 19:14

    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]
    

提交回复
热议问题