views:

42

answers:

2
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'
A: 

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'.

Mark Byers
But I have to keep the key as(1,1), (4,5)..in this format so that I can go back to my path by referencing this key and get the direction related to this key. I cant change the finction "def directionvector"...I am not allowed to do that....
Shilpa
I think you're confusing keys with values. The keys are "west", "north", etc, and the values are (1, 1), (4, 5), etc.
ars
@Shilpa: Why are you not allowed to change the definition? Your teacher said this? Besides you don't need to change the definition, just how it is called.
Mark Byers
my teacher told me to make changes in only 1 file....dont touch other files...Bcoz they asked me to submit my code only..and they will run it in their system with other files keeping unchanged...
Shilpa
my dict output is in this order: {(5, 4): 'North', (1, 3): 'West', (5, 5): 'North', (4, 5): 'East'............so on....so here the key is (5,4) and value is North...is it right??
Shilpa
+1  A: 

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
ars