I am using psycopg2 to access the data from the Postgres database. I am using psycopg2.extras.DictCursor for getting the data in a dict-like form using the following query:
try:
self.con = psycopg2.connect(dbname=self.db, user=self.username,
host=self.host, port=self.port)
cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("SELECT * FROM card")
result = cur.fetchall()
print result
I get the output as a list:
[['C01', 'card#1', 'description#1', '1'], ['C02', 'card#2', 'description#2', '1']]
However, I want the column names as well. I read another similar question here, but on trying the following I get a KeyError:
cur.execute("SELECT * FROM card")
for row in cur:
print(row['column_name'])
However, the following works:
cur.execute("SELECT * FROM card")
for row in cur:
print(row['id'])
Output:
C01
C02
Any ideas on how I can get the column names as well?