I have a very simple and small db table with 2 columns only: Id and name. Given the id, I have to find and return the corresponding name. I want to save the contents in a dictionary and look for the corresponding value from there instead of querying the database each time. I have came across this How to convert SQL query results into a python dictionary but they are aiming to save each row as a dict, whilst I think I do not need a list of dictionaries just a dict with key value pairs.
def get_name(db_conn):
cursor = db_conn.cursor()
cursor.execute("SELECT id, name FROM table")
rows = cursor.fetchall()
d = {}
for row in rows:
id = row[0]
name = row[1]
d[id]= name
print(d)
What would be the best approach given the task I have?