4

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?

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
mangom
  • 467
  • 1
  • 3
  • 20

1 Answers1

3

to get all column names you can use the mehtod keys for row item, for example:

cur.execute("SELECT * FROM card")
result = cur.fetchall()
keys = list(result[0].keys()) if result else []
for row in result:
    for key in keys:
        print(row[key])
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • 2
    Just wanted to add, to get the column names, we need to convert keys to a list. Curently, it returns an iterator object – mangom Apr 11 '19 at 09:14