DictCursor doesn't seem to work under psycopg2
Use RealDictCursor
:
import psycopg2.extras
cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cur.execute("SELECT * from review")
res = cur.fetchall()
This gives you a list with rows as real python dictionaries instead of "advanced psycopg2 list".
res = cur.fetchall()
makes res
a list of psycopg2.extras.DictRow
s.
Alternatively, instead of calling cur.fetchall
you can take advantage of the fact that cur
is an iterable:
cur.execute("SELECT * from review")
for row in cur:
print(row['column_name'])
and thus you'll be able to access the data with dict
-like syntax.
Another solution would be to use the Named Tuple Cursor since the Real Dict Cursor will break any query that uses integer indicies as explained in its documentation.
With Named Tuple Cursors, you can access them with dot syntax like so:
import psycopg2
import psycopg2.extras
cur = conn.cursor(cursor_factory = psycopg2.extras.NamedTupleCursor)
cur.execute("SELECT * from review")
res = cur.fetchone()
res.key1
res.key2
This keeps things tidy and won't break anything as far as I know.