迭代字典我在我註冊一些數據的數據庫。我嘗試選擇所有行並嘗試將表中的每一行都放入字典中,但似乎無法做到這一點。具有在Python
這是代碼:
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)
這是我得到的結果是:
{"Server Name": ["Dell1", "Dell2"], "Server Price": [149, 151]}
不過,我想看到的結果是這樣的:
{"Server Name" : Dell1, "Server Price": 149}
{"Server Name" : Dell2, "Server Price": 151}
能
人幫我?
這個信息,我需要把它解析爲JSON,所以我必須將結果作爲dictionanry沒有字典的列表,以便我能得到的鑰匙(服務器,服務器的價格)和它們的值 幫助請 – imoum 2013-03-07 16:50:54
呃,不,我不能,因爲這沒有意義。你最初有一本字典,並要求幫助獲取字典列表。所以現在我不明白你真正想要什麼。 – 2013-03-07 16:59:27