2013-03-04 134 views
1

迭代字典我在我註冊一些數據的數據庫。我嘗試選擇所有行並嘗試將表中的每一行都放入字典中,但似乎無法做到這一點。具有在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} 

人幫我?

回答

2
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) 
+0

這個信息,我需要把它解析爲JSON,所以我必須將結果作爲dictionanry沒有字典的列表,以便我能得到的鑰匙(服務器,服務器的價格)和它們的值 幫助請 – imoum 2013-03-07 16:50:54

+0

呃,不,我不能,因爲這沒有意義。你最初有一本字典,並要求幫助獲取字典列表。所以現在我不明白你真正想要什麼。 – 2013-03-07 16:59:27

0

請試試這個

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) 

而是附加列出的,我們正在創建的本地詞典和添加本地字典來響應。

+0

這個信息,我需要把它解析爲JSON,所以我必須將結果作爲dictionanry沒有字典的列表,以便我能得到的鑰匙(服務器,服務器的價格)和它們的值幫助,請 – imoum 2013-03-07 16:51:11

+0

詞典將採取'鍵,值'對,存儲值沒有任何鍵你必須使用列表或元組。列表和元組是訂單數據結構。 – Nilesh 2013-03-08 05:08:37