KeyError:12使用本机python时

问题描述 投票:0回答:2

试图创建一个数据结构,使用部门作为“关键”,并将该部门的请求总数作为“值”,但我正在解决12的关键错误。(控制台显然说错了

total_department_requests = total_for_department[products[entry]["department_id"]] + products[entry]["metrics"]["request_count"]
total_for_department = {}
for entry in products:   

   #print entry
   if entry not in total_for_department:
      #print "it's new"
      total_for_department.update({products[entry]["department_id"] : products[entry]["metrics"]["request_count"]} )
   else:
      total_department_requests = total_for_department[products[entry]["department_id"]] + products[entry]["metrics"]["request_count"] 
      # print total_department_requests
      total_for_department.update({products[entry]["department_id"] : total_department_requests })

print(total_for_department)

任何帮助将非常感激

python database bigdata keyerror
2个回答
1
投票

entry不是索引 - 它是products数组中的实际内容。当你做products[entry]时,for entry in products没有意义

如果您想要索引,请使用enumerate

for i, entry in enumerate(products):

1
投票

首先,我建议您重新格式化数据。如果找不到keyError,那就意味着你太复杂了。

无论如何,KeyError“12”让我觉得你正在尝试更新一个尚不存在的特定部门ID的条目。

事实上,在更新["department_id"]之前,您不会检查products[entry]["department_id"]是否存在

实际上,现在我看着它,似乎你正在检查它是否不存在,如果它不存在你正在更新它,而不是创建它。尝试切换这两个动作。

也许试试吧

if products[entry]["department_id"] in total_for_department
© www.soinside.com 2019 - 2024. All rights reserved.