使用字典时如何避免KeyError?
问题描述:
现在,我想编写一个汇编程序,但我不断收到此错误:使用字典时如何避免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)
帮助表示赞赏。
答
您通常使用.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
方法使代码更短,更快,所以我不会实际使用后一种方法。这只是为了指出为什么你的代码失败。
+0
MSeifert,非常感谢:D –
答
registerTable中没有键'LD'。可以把一个尝试except块:
try:
a=registerTable[item]
...
except KeyError:
pass
答
您正在查看字典中是否存在潜在密钥item
item
。您只需在测试中删除查找。
if item in functionTable:
...
虽然这甚至可以改善。
它看起来像你试图查找项目,或默认为'00'。 Python字典具有内置函数.get(key, default)
以尝试获取值,或默认为其他值。
尝试:
functionField = functionTable.get(item, '00')
registerField = registerTable.get(item, '00')
莫非你要仔细检查缩进是正确的?我把它格式化为代码,但是如果这是想要的缩进总是很难确定。 :) – MSeifert
就在旁边...你可以在范围(16)中对值为'valueTable = {str(n):format(n,'04b')'' - 这样就可以更容易地改变范围,复制/粘贴错误或以其他方式输入不正确的值和更少的屏幕空间... –