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)
but when I do this return, it gives me an error and final is the directory that I have made with lists of keys and values
The error is:
File "line 212, in directionToVector
dx, dy = Actions._directions[direction]
KeyError: 'W'
2 Answers 2
Actions._directions is presumably a dictionary, so the line:
dx, dy = Actions._directions[direction]
at runtime (based on the error message) is:
dx, dy = Actions._directions["W"]
and it's complaining that there's no key "W" in that dictionary. So you should check to see that you've actually added that key with some value in there. Alternatively, you can do something like:
dx, dy = Actions._directions.get(direction, (0, 0))
where (0, 0) can be any default value you choose when there's no such key. Another possibility is to handle the error explicitly:
try:
dx, dy = Actions._directions[direction]
except KeyError:
# handle the error for missing key
Comments
This error
KeyError: 'W'
means that the key you requested ('W') is not one of the keys that are stored in the dictionary. This is because your dictionary key is 'west' not 'W' (see your previous question). Try this instead:
key = { 'N' : 'north', 'S' : 'south', 'E' : 'east', 'W' : 'west' }[direction]
dx, dy = Actions._directions[key]
Alternatively, make sure you pass the string 'west' to directionToVector and not the string 'W'.
while not stack.isEmpty():looks a bit betterwhile stack:assuming it is a list.while stack.isEmpty() != 1:? And where do you calldirectionToVector?