使用词典时如何避免KeyError?

Wig*_*ier 12 python dictionary keyerror

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

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)
Run Code Online (Sandbox Code Playgroud)

感谢帮助.

MSe*_*ert 30

您通常使用.get默认值

get(key[, default])

如果key在字典中,则返回key的值,否则返回default.如果未给出default,则默认为None,因此此方法永远不会引发KeyError.

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

for item in newS:
    functionField = functionTable.get(item, "00")
    registerField = registerTable.get(item, "00")
    print(functionField + registerField)
Run Code Online (Sandbox Code Playgroud)

打印:

1000
0000
0000
Run Code Online (Sandbox Code Playgroud)

如果要显式检查密钥是否在字典中,则必须检查密钥是否在字典中(不进行索引!).

例如:

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"
Run Code Online (Sandbox Code Playgroud)

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


小智 6

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

if item in functionTable:
    ...
Run Code Online (Sandbox Code Playgroud)

尽管这甚至可以改进。

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

尝试:

functionField = functionTable.get(item, '00')
registerField = registerTable.get(item, '00')
Run Code Online (Sandbox Code Playgroud)


akp*_*akp 5

registerTable 中没有键“LD”。可以试试除了 block :

try:
   a=registerTable[item]
      ...
except KeyError:
   pass
Run Code Online (Sandbox Code Playgroud)