KeyError - python 字典

KeyError - python dictionaries

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

"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

已在评论中解决:

When you retrieved the dictionary from the file, did you also apply int() to this key?
12345670 and "12345670" are not equivalent keys. – jasonharper

Yeah I just thought maybe that was the reason and i resolved the problem, thanks for the help :) i converted the variable to an int before i used it – Heather Lara