Skip to main content
 首页 » 编程设计

python之python代码执行出错-字典问题

2025年05月04日8me-sa

while stack.isEmpty() != 1: 
             fin = stack.pop() 
         print fin            - output is (1,1) 
         k = final.get(fin) 
         return k 
 
def directionToVector(direction, speed = 1.0): 
    dx, dy =  Actions._directions[direction] 
    return (dx * speed, dy * speed) 
  directionToVector = staticmethod(directionToVector) 

但是当我返回时,它给我一个错误,final 是我用键和值列表创建的目录

错误是:

File "line 212, in directionToVector 
    dx, dy =  Actions._directions[direction] 
KeyError: 'W' 

请您参考如下方法:

Actions._directions 大概是一个字典,所以行:

dx, dy =  Actions._directions[direction] 

在运行时(基于错误信息)是:

dx, dy =  Actions._directions["W"] 

它提示说字典中没有键“W”。所以你应该检查你是否真的添加了那个带有一些值的键。或者,您可以执行以下操作:

dx, dy =  Actions._directions.get(direction, (0, 0)) 

其中 (0, 0) 可以是您在没有此类键时选择的任何默认值。另一种可能性是显式处理错误:

try: 
    dx, dy =  Actions._directions[direction] 
except KeyError: 
    # handle the error for missing key