使用字典时如何避免 KeyError?

How do I avoid KeyError when working with dictionaries?

现在我正在尝试编写一个汇编程序,但我不断收到此错误:

Traceback (most recent call last):
  File "/Users/Douglas/Documents/NeWS.py", line 44, in 
    if item in registerTable[item]:
KeyError: 'LD'

我目前有这个代码:

functionTable = {"ADD":"00",
         "SUB":"01",
         "LD" :"10"}

registerTable = {"R0":"00",
         "R1":"00",
         "R2":"00",
         "R3":"00"}

accumulatorTable = {"A"  :"00",
            "B"  :"10",
            "A+B":"11"}

conditionTable = {"JH":"1"}

valueTable = {"0":"0000",
          "1":"0001",
          "2":"0010",
          "3":"0011",
          "4":"0100",
          "5":"0101",
          "6":"0110",
          "7":"0111",
          "8":"1000",
          "9":"1001",
          "10":"1010",
          "11":"1011",
          "12":"1100",
          "13":"1101",
          "14":"1110",
          "15":"1111"}

source = "LD R3 15"

newS = source.split(" ")

for item in newS:

        if item in functionTable[item]:
            functionField = functionTable[item]
        else:
            functionField = "00"

        if item in registerTable[item]:
            registerField = registerTable[item]
        else:
            registerField = "00"

print(functionField + registerField)

感谢帮助。

registerTable 中没有关键字'LD'。可以放一个try except block :

try:
   a=registerTable[item]
      ...
except KeyError:
   pass

您通常使用 .get 默认值

get(key[, default])

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

所以当你使用 get 时,循环看起来像这样:

for item in newS:
    functionField = functionTable.get(item, "00")
    registerField = registerTable.get(item, "00")
    print(functionField + registerField)

打印:

1000
0000
0000

如果您想明确检查键是否在字典中,您必须检查键是否在字典中(没有索引!)。

例如:

if item in functionTable:   # checks if "item" is a *key* in the dict "functionTable"
    functionField = functionTable[item]  # store the *value* for the *key* "item"
else:
    functionField = "00"

但是get方法使代码更短更快,所以我实际上不会使用后一种方法。只是为了指出您的代码失败的原因。

您要查看 item 的字典中是否存在潜在键 item。您只需要删除测试中的查找。

if item in functionTable:
    ...

虽然这甚至可以改进。

您似乎在尝试查找该项目,或默认为“00”。 Python 字典有内置函数 .get(key, default) 来尝试获取一个值,或者默认为其他值。

尝试:

functionField = functionTable.get(item, '00')
registerField = registerTable.get(item, '00')