2015-11-17 28 views
1

我有一个像下面一起列名从SQL表值列表在Python

---------------------------------- 
    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")然后SQL表尝试使用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')] 

但我需要这个表作为列表蟒蛇像下面

[{'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'}] 

我该怎么做?

回答

3

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

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

它的工作。谢谢@Daniel Roseman – Prabhakar

0

试试这个

Key_value_pair = dict(list_of_tuple_from_the_database)