Reputation: 423
I have a database in which I registered some data. I tried to select all rows and try to put every row of my table into a dictionary, but I can't seem to do that.
This is the code:
db = MySQLdb.connect("localhost","root","aqw","PFE_Project" )
cursor = db.cursor()
sql = "SELECT * FROM ServerComponents"
try:
cursor.execute(sql)
results = cursor.fetchall()
nbre_row = cursor.rowcount
server_name = []
server_price = []
for row in results:
server_id = row[0]
server_name.append(row[1])
core_number = int(row[2])
clock_speed = int(row[3])
ram = int(row[4])
rom = row[5]
hdd = int(row[6])
video_card = row[7]
cache_memory = row[8]
# calculation metric is a function that i used to calculate the server prize
p = calculations_metric (core_number, clock_speed, ram, hdd, video_card)
server_price.append(p)
try :
# i wanna the attribute "response" be iterative
response = {"Server Name" : server_name , "Server Price" : server_price }
except :
print "error in response"
except:
print "Error: unable to fetch data"
print(response)
This is the result I got:
{"Server Name": ["Dell1", "Dell2"], "Server Price": [149, 151]}
But the result that I want see is like this:
{"Server Name" : Dell1, "Server Price": 149}
{"Server Name" : Dell2, "Server Price": 151}
Can anyone help me?
Upvotes: 1
Views: 92
Reputation: 599610
servers = []
for row in results:
result = {}
result['server_name'] = row[1])
p = calculations_metric (core_number, clock_speed, ram, hdd, video_card)
result['server_price'] = p
servers.append(result)
Upvotes: 2
Reputation: 21243
Please try this
db = MySQLdb.connect("localhost","root","aqw","PFE_Project" )
cursor = db.cursor()
sql = "SELECT * FROM ServerComponents"
response = []
try:
cursor.execute(sql)
results = cursor.fetchall()
nbre_row = cursor.rowcount
for row in results:
local_dict = {}
server_id = row[0]
local_dict["Server Name"] = row[1]
core_number = int(row[2])
clock_speed = int(row[3])
ram = int(row[4])
rom = row[5]
hdd = int(row[6])
video_card = row[7]
cache_memory = row[8]
# calculation metric is a function that i used to calculate the server prize
p = calculations_metric (core_number, clock_speed, ram, hdd, video_card)
local_dict["Server Price"] = p
response.append(local_dict)
except:
print "Error: unable to fetch data"
print(response)
Instead of appending to list, we are creating local dict and adding that local dict to response.
Upvotes: 0