使用字典时如何避免KeyError? [英] How do I avoid KeyError when working with dictionaries?

查看:180
本文介绍了使用字典时如何避免KeyError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我正在尝试编写汇编代码,但我一直收到此错误:

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'

我目前有以下代码:

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)

我们非常感谢您。

推荐答案

您通常使用 .get 默认值

You generally use .get with a default


get(key [,默认])

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

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时循环看起来像这样:

So when you use get the loop would look like this:

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

其中打印:

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!).

例如:

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 方法使代码更短,更快,因此我实际上不会使用后一种方法。只是为了指出您的代码为什么失败。

But the get method 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.

这篇关于使用字典时如何避免KeyError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆