Print column name as headings with bd postgresql and python

0

I have the following code of a PostgreSQL table, I need you to print the name of columns as a header, with Tabulate and Python, I only get the numbering of the columns as a header, I do not know why:

cur.execute("""select * from admin_eps""")

rows = [cur.fetchall()]

for row in rows:
    print(tabulate(row, headers="keys", tablefmt='fancy_grid', stralign='left'))

This is the exit report:

│   0 │         1 │ 2           │ 3                │ 4        │      5 │      6 │ 7                   │ 8                │
╞═════╪═══════════╪═════════════╪══════════════════╪══════════╪════════╪════════╪═════════════════════╪══════════════════╡
│   2 │ 890890890 │ Medimas     │ carr 26 n 10-20  │ Bogota   │ 520520 │ 311311 │ [email protected] │ wwww.medimas.com │
├─────┼───────────┼─────────────┼──────────────────┼──────────┼────────┼────────┼─────────────────────┼──────────────────┤
│   1 │     54321 │ COOMEVA EPS │ Calle 30 n 33-30 │ Medellin │ 252444 │ 320320 │ [email protected] │ www.coom.com     │
╘═════╧═══════════╧═════════════╧══════════════════╧══════════╧════════╧════════╧═════════════════════╧══════════════════╛
    
asked by Jsierra2017 01.03.2018 в 17:29
source

1 answer

1

That happens because you're using headers='keys' . When you use this, the dictionary keys are used, but since it is not a dictionary, its index is used.

Try using your own headers:

cur.execute("""select * from admin_eps""")

rows = [cur.fetchall()]
headers = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

for row in rows:
    print(tabulate(row, headers=headers, tablefmt='fancy_grid', stralign='left'))

Another option you can try is to use RealDictCursor :

from psycopg2.extras import RealDictCursor

# ...    
cur = conn.cursor(cursor_factory=RealDictCursor)
cur.execute("""select * from admin_eps""")

rows = [cur.fetchall()]

for row in rows:
    print(tabulate(row, headers="keys", tablefmt='fancy_grid', stralign='left'))
    
answered by 01.03.2018 / 17:40
source