psycopyg2 – Get dictionary like query results

Wondering how life would be much easier if you could get the query resultset to be a dictionary and you could get the value by using a keyword on the dictionary. psycopg2 by default returns resultset as a tuple so you have to use row[0], etc to get the values. In order to use row[‘column_name’] from the result, you’ll have to use the extras module provided in the psycopg2. Initiate the cursor accordingly and you’ll be able to get the results in form of dictionary.

import psycopg2
import psycopg2.extras

DB_CONNECTION_STRING = "host=%s dbname=%s user=%s password=%s" % (DB_HOST, DB_DATABASE, DB_USER, DB_PASSWORD)
dbConn = psycopg2.connect(DB_CONNECTION_STRING)
cur = dbConn.cursor(cursor_factory = psycopg2.extras.DictCursor)
qSelect = "SELECT server, data, report_date FROM kw_server_raw WHERE processed = FALSE"
results = cur.fetchall()
for row in results:
	print row['server']

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s