theObserver
theObserver

Reputation: 127

Why is Python 3x returning a list instead of a dict?

I'm scratching my head over this piece of code which runs a SQL query and formats the result into a dict. But the result is returned as a list instead of a dict and I can't understand why:

def runSqlQuery(sqlCommand, connectString="xxxxxxxxxxxxxxx"):
    connection = cx_Oracle.connect(connectString)
    cursor = connection.cursor()
    cursor.execute(sqlCommand)
    #use the cursor column descriptions to create readable dict of results
    columns = [i[0] for i in cursor.description]  
    result = [dict(zip(columns, row)) for row in cursor]
    print (type(result))
    return result 

The function returns nicely formatted SQL results like: [{'Column1': '123', 'Name': 'Bob', 'Age': '39'}]

But why is it a list when I'm clearly using the dict keyword? Is it due to the [] brackets?

Upvotes: 0

Views: 75

Answers (1)

Jon Kiparsky
Jon Kiparsky

Reputation: 7753

result = [dict(zip(columns, row)) for row in cursor]

this line is a list comprehension - it creates a list by iterating over the rows in cursor and creating a dict for each row. So the result is a list of dicts

I think you will find that this line

all([isinstance(item, dict) for item in result])

produces a True result - that is, each of the items in the list is a dict

Upvotes: 2

Related Questions