Search code examples
pythonsql-serverpython-2.7pymssql

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


I have a SQL table like below

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

I have used cursor.execute("select top 5 Key, Value from TestTable") and then tried to convert as list using mylist = list(cursor)

But I am getting like

[(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')]

But I need this table as list in python like below

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

How can I make that?


Solution

  • You need to use a dict cursor - see the pymssql docs.

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