Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2.extras.DictCursor does not give me column names

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?

like image 568
Mihika Avatar asked Dec 05 '25 16:12

Mihika


1 Answers

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])

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!