簡體   English   中英

從SQL表獲取值以及列名作為Python中的列表

[英]Get values from SQL table along with column name as list in Python

我有一個如下的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'}]

我該怎么做?

您需要使用dict光標-請參見pymssql文檔

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

嘗試這個

Key_value_pair = dict(list_of_tuple_from_the_database)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM