python - Python 中有一个迭代字典

标签 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}

有人可以帮助我吗?

最佳答案

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)

关于python - Python 中有一个迭代字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198411/

相关文章:

python - for 循环不适用于 if else 条件

python - 高性能计算所有可能组合的最小二乘方差(n个列表)

java - 如何在迭代java列表时向前查找 'n'元素?

找不到Python包,没有名为 "coroapi"的模块

python - 转录长音频文件不起作用

python - 获取 ssh 服务器的 64 进制主机 key

python - 如何使用 Python 的 doctest-package 测试字典相等性?

python - 是否有一个特殊值不会在字典中插入键

python - 为什么使用 for 循环将 '\n' 存储为一项?

c++ - std::list 或 std::multimap