Search code examples
pythonsqlloopsdictionarycursor

Dictionary structure from SQL cursor


Suppose I had a SELECT SQL query and I wanted to return a structure e.g. for first 3 rows:

{
0: {'ColName0': 'Col1RowValue0', 'ColName1': 'Col1RowValue0'},
1: {'ColName0': 'Col0RowValue1', 'ColName1': 'Col1RowValue1'},
2: {'ColName0': 'Col0RowValue2', 'ColName1': 'Col1RowValue2'}
...
}

I get close with the below but I can't get the outer index structure to work: {0:{},1:{}}

with read_con.cursor() as cur:
    cur.execute(DONOR_SELECT)
    column_names = [col[0] for col in cur.description]
    temp_d = [dict(zip(column_names, row))  
        for row in cur.fetchall()]
print(temp_d)

cursor is from pyodbc


Solution

  • You need a dict comprehension with enumerate

    temp_d = {i : dict(zip(column_names, row)) for i, row in enumerate(cur.fetchall())}