0

I'm using python, psycopg2, and postgresql. Looking for a way to reference the column directly by name. See example below.

TABLE testtable
testcolumn1 | testcolumn2 | testcolumn3 
------------+-------------+------------
 horse      | cow         | goat
 simple     | code        | test
 cant       | figure      | this


conn = psycopg2.connect("dbname='test' user='me' password='pass'")
cursor = conn.cursor()
cursor.execute("select * from testtable")
cursor_rows = cursor.fetchall()
for row in cursor_rows:    
    print(row['testcolumn2'])

# the result of the loop should be 
cow
code
figure

Is there a way to directly reference by column name like this?

Thank you for any help

1 Answer 1

2

Try using

import psycopg2.extras
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

Documentation here. There is also support for named tuples.

Sign up to request clarification or add additional context in comments.

1 Comment

Since the default is tuples, which are immutable, they will certainly be a bit more lightweight than dicts. I reckon the improved readability of the code more than makes up for that though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.