从Python表中获取SQL表中的值以及列名作为列表

时间:2015-11-17 12:28:15

标签: python sql-server python-2.7 pymssql

我有一个如下表所示的SQL表

----------------------------------
     Key         |    Value
----------------------------------
Ralph Williams      Football
Michael Tippett     Basketball
Edward Elgar        Baseball
Rebecca Clarke      Netball
Ethel Smyth         Badminton

我使用了cursor.execute("select top 5 Key, Value from TestTable"),然后尝试使用mylist = list(cursor)

转换为列表

但我变得像是

[(u'Ralph Williams', u'Football'), (u'Michael Tippett', u'Basketball'), (u'Edward Elgar', u'Baseball'), (u'Rebecca Clarke', u'Netball'), (u'Ethel Smyth', u'Rugby')]

但是我需要这个表作为python中的列表,如下面的

[{'Key':'Ralph Williams', 'Value':'Football'}, {'Key':'Michael Tippett', 'Value':'Basketball'}, {'Key':'Edward Elgar', 'Value':'Baseball'}, {'Key':'Rebecca Clarke', 'Value':'Netball'}, {'Key':'Ethel Smyth', 'Value':'Rugby'}]

我该怎么做?

2 个答案:

答案 0 :(得分:4)

您需要使用dict光标 - 请参阅pymssql docs

cursor = conn.cursor(as_dict=True)
cursor.execute(...)

答案 1 :(得分:0)

试试这个

Key_value_pair = dict(list_of_tuple_from_the_database)