【问题标题】:KeyError - python dictionariesKeyError - python 字典
【发布时间】:2017-05-10 20:16:58
【问题描述】:

我在 Python 中使用字典并尝试引用其中一个数据类别,但是在运行代码时出现 keyerror。

“Restock_Item”将是一个八位数字,例如字典中的“12345670”,因此使用

stock[restock_item]['STOCK_LEVEL']

它会像这样引用字典:

stock[12345670]['STOCK_LEVEL']

但是当我这样做时,我得到了错误:

KeyError: 12345670

代码如下:

restock_item = input("\nPlease enter the gtin code of the product you wish to restock. ")
    if restock_item.isdigit() == True:

        restock_level = input("How many items would you like to restock? ")
        while restock_item.isdigit() == True:

            restock_item = int(restock_item)
            newStockLevel = int(stock[restock_item]['STOCK_LEVEL']) # This is the line that gets the key error
            newStockLevel = newStockLevel + restock_level
            stock[restock_item]['STOCK_LEVEL'] = newStockLevel

【问题讨论】:

  • KeyError 表示您的字典中没有任何项目具有该键。您确定要检索的内容存在吗?
  • print 字典。您会发现您正在尝试访问一个不存在的条目。没什么可做的
  • 您是在创建库存[restock_item],还是应该已经存在?或者除非它已经存在,否则你要创建它?
  • 当您从文件中检索字典时,您是否也将int() 应用于此键? 12345670"12345670" 不是等效键。
  • 你可能想 1/ 写下这个答案 2/ 接受你自己的答案,这样这个案例就结束了。

标签: python dictionary keyerror


【解决方案1】:

在cmets中解决:

当您从文件中检索字典时,您是否也将 int() 应用于此键?
12345670 和“12345670”不是等效键。 ——杰森哈珀

是的,我只是认为这可能是原因,我解决了问题,感谢您的帮助 :) 我在使用之前将变量转换为 int – Heather Lara

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多