在Python中有一个迭代字典

时间:2013-03-04 09:36:38

标签: python dictionary iteration

我有一个数据库,我在其中注册了一些数据。我试图选择所有行并尝试将表格的每一行放入字典中,但我似乎无法做到这一点。

这是代码:

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 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)

我们不是附加到列表,而是创建本地字典并将本地字典添加到响应中。