从 SQL table 中获取值以及列名作为 Python 中的列表
Get values from SQL table along with column name as list in Python
我有一个 SQL table 如下所示
----------------------------------
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')]
但我需要这个 table 作为 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'}]
我该怎么做?
您需要使用字典游标 - 请参阅 pymssql docs。
cursor = conn.cursor(as_dict=True)
cursor.execute(...)
试试这个
Key_value_pair = dict(list_of_tuple_from_the_database)
我有一个 SQL table 如下所示
----------------------------------
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')]
但我需要这个 table 作为 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'}]
我该怎么做?
您需要使用字典游标 - 请参阅 pymssql docs。
cursor = conn.cursor(as_dict=True)
cursor.execute(...)
试试这个
Key_value_pair = dict(list_of_tuple_from_the_database)