Skip to content

Instantly share code, notes, and snippets.

@grizmio
Created July 21, 2020 03:01
Show Gist options
  • Save grizmio/1a1367fba82b85a57e534d6b463be146 to your computer and use it in GitHub Desktop.
Save grizmio/1a1367fba82b85a57e534d6b463be146 to your computer and use it in GitHub Desktop.
pg8000 cursor results as dictionary
import pg8000
# thanks to: Sucas Venior https://stackoverflow.com/questions/58658690/retrieve-query-results-as-dict-in-sqlalchemy
def rows_as_dicts(cursor):
"""convert tuple result to dict with cursor"""
col_names = [i[0].decode() for i in cursor.description]
for row in cursor:
x = dict(zip(col_names, row))
yield x
# Better with with :-)
con = pg8000.connect(user="foo", password="bar")
cur = con.cursor()
cur.execute('select * from table')
rows = rows_as_dicts(cur)
for row in rows:
print(row)
cur.close()
con.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment