Created
July 21, 2020 03:01
-
-
Save grizmio/1a1367fba82b85a57e534d6b463be146 to your computer and use it in GitHub Desktop.
pg8000 cursor results as dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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