【问题标题】:KeyError: 12 when using native pythonKeyError:使用本机 python 时为 12
【发布时间】:2019-04-02 08:49:45
【问题描述】:

尝试创建一个使用部门作为“键”并将该部门的请求总数作为“值”的数据结构,但我得到一个 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 keyerror


    【解决方案1】:

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

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

    for i, entry in enumerate(products):
    

    【讨论】:

    • 有点困惑。条目是我的字典,它有一个键/值,我使用它来使用产品的 id 来引用产品信息。
    • 如果products 是一个字典,那么我猜12 一定不是那个字典中的键
    【解决方案2】:

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

    无论如何,KeyError "12" 让我认为您正在尝试更新尚不存在的特定部门 ID 的条目。

    其实你在更新products[entry]["department_id"]之前并没有检查["department_id"]是否存在

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

    不妨试试

    if products[entry]["department_id"] in total_for_department
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      相关资源
      最近更新 更多