Home > Back-end >  MySQL dump a table or saving table contents as a python dictionary
MySQL dump a table or saving table contents as a python dictionary

Time:12-14

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?

CodePudding user response:

Dictionary comprehensions should be straight forward enough...

d = { row[0]: row[1] for row in cursor.fetchall() }

or...

d = { id: name for (id, name) in cursor.fetchall() }

This processes every row in cursor.fetchall() and yields key: value pairs directly into a dictionary.

It's very similar to your loop, but the looping is done in C rather than natively in python.

  • Related