Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve the data from MySQL database, in dictionary format in python

Tags:

python

mysql

import MySQLdb
def Network():

    dict = {'CISCO' : 'NEXUS', 'JUNIPER' : 'JUNO', 'Alcatel' : 'Alc' }


    #len(dict)
    return (dict)



def db_store(variable):
    con = MySQLdb.connect("localhost","root","root","fs_company" )
    cur = con.cursor()
    for key,value in variable.items():
        cur.execute('''INSERT into google (name, company) values (%s, %s)''', (key, value))
        con.commit()
    cur.execute("""SELECT * FROM google""")
    variable = cur.fetchall()
    #print variable



variable = Network()
db_store(variable)

I have above code to store the data to mysql database, I want to retrieve the data from database in dictionary format. need help for the same

like image 742
user3804186 Avatar asked Jun 12 '26 08:06

user3804186


1 Answers

You are missing only one line. You can convert variable into dict like this:

cur.execute("""SELECT * FROM google""")
out = cur.fetchall()
variable = {key:val for key,val in out}
print(variable)
like image 189
kecer Avatar answered Jun 13 '26 22:06

kecer