From 941ebc4a24d58d3c0290cee2a04741b28d8be5be Mon Sep 17 00:00:00 2001 From: Dustin Thomas Date: Sun, 14 Jan 2024 15:25:45 -0600 Subject: [PATCH] add a function to convert a tuple into a dictionary --- database.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/database.py b/database.py index 2e5ba6f..cbff64d 100644 --- a/database.py +++ b/database.py @@ -66,6 +66,19 @@ class DBConnector: finally: return result + def _read_dict(self) -> list[dict]: + """Read the cursor as a list of dictionaries. psycopg2 defaults to using a list of tuples, so we want to convert + each row into a dictionary before we return it.""" + cols = [i.name for i in self.cur.description] + results = [] + for row in self.cur: + row_dict = {} + for i in range(0, len(row)): + if row[i]: + row_dict = {**row_dict, cols[i]: row[i]} + results.append(row_dict) + return results + def read(self, **kwargs) -> list[dict]: """Read rows from a database that match the specified filters.