Python 使用字典时如何避免 KeyError?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46024562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:25:11  来源:igfitidea点击:

How do I avoid KeyError when working with dictionaries?

pythondictionarykeyerror

提问by Wigan Pier

Right now I'm trying to code an assembler but I keep getting this error:

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

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

I currently have this code:

我目前有这个代码:

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)

Help is appreciated.

帮助表示赞赏。

回答by MSeifert

You generally use .getwith a default

您通常使用.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(key[, default])

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

So when you use getthe loop would look like this:

所以当你使用get循环时会是这样的:

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

which prints:

打印:

1000
0000
0000


If you want to do the explicit check if the key is in the dictionary you have to check if the key is in the dictionary (without indexing!).

如果你想显式检查键是否在字典中,你必须检查键是否在字典中(没有索引!)。

For example:

例如:

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"

But the getmethod makes the code shorter and faster, so I wouldn't actually use the latter approach. It was just to point out why your code failed.

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

回答by akp

There is no key 'LD' in registerTable. Can put a try except block :

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

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

回答by Kyle P

You are looking to see if the potential key itemexists in in dictionary at item. You simply need to remove the lookup in the test.

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

if item in functionTable:
    ...

Though this could even be improved.

虽然这甚至可以改进。

It looks like you try to look up the item, or default to '00'. Python dictionaries has the built in function .get(key, default)to try to get a value, or default to something else.

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

Try:

尝试:

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