0

I am learning Python starting with 2.7 and working with a dictionary, wanted to execute a function in my program when the key is called. Looked on the net quite a bit, but either is not related or may just simply not understanding. Below is what I started doing as a concept while using one of my favorite games to learn.

Below is a more accurate representation of where I am currently at:

myDict = {
    'descript': "This is some text to be printed",
    'NORTH': northOfHouse (not sure if this is correct format)
    }

def westOfHouse():

    print myDict['descript]

    if action == ('n' or 'north'):
        myDict['NORTH]() (Not sure about proper format)
    else:
        print "there is no path in that direction

I have gotten the basic stuff to work when using a dictionary such as printing strings, modifying values, etc... just not getting how to make functions execute.

martineau
  • 119,623
  • 25
  • 170
  • 301
Darwin
  • 103
  • 2
  • 6
  • 1
    what error are you getting? – Astrom Apr 19 '17 at 14:44
  • 1
    Possible duplicate of [Python: Using a dictionary to select function to execute](http://stackoverflow.com/questions/9168340/python-using-a-dictionary-to-select-function-to-execute) – FamousJameous Apr 19 '17 at 14:45
  • You're calling currently `myDef` *when creating the dictionary*, did you actually want something like `myDict['key']()` to work? – jonrsharpe Apr 19 '17 at 14:45
  • `'key': myDef()`. You're immediately calling the function inside the dictionary. Remove the parentheses. – Carcigenicate Apr 19 '17 at 14:46
  • calling looking up the value to a given key in a python dictionary returns the value associated with that key. This object can be a function no problem, however you then need to tell it to execute by calling it like `myResult = myDict[key]()`. – Chris Apr 19 '17 at 14:46
  • I am wanting to, if possible, to call a function that is identified in the dictionary and then go to that function in the program and execute its code..if that makes more sense. – Darwin Apr 19 '17 at 14:48
  • 1
    when setting a key:value such as: 'NORTH': northOfhouse , I get name not defined. I also tried 'NORTH': northOfHouse() . So 1) not sure what the proper identification of a function should look like in a dictionary, and 2) how to properly call the key:value from the program. I have seen what Chris has posted with the myResult = myDict[key](), but could not make it work – Darwin Apr 19 '17 at 14:50
  • 1
    `northOfHouse` needs to be the name of a callable, like a function, so you can call it if the `action` matches. – martineau Apr 19 '17 at 15:10
  • Once you've defined `northOfHouse`, the rest of what you're doing looks basically correct. – martineau Apr 19 '17 at 15:29

1 Answers1

1

As a very simplified demo of what it you are attempting to do, look at the following:

def northOfHouse():
    print "north"
    action = raw_input()
    myDict[action]()
def westOfHouse():
    print "west"
    action = raw_input()
    myDict[action]()

myDict = {
    "WEST": westOfHouse,
    "NORTH": northOfHouse
}

action = raw_input()
myDict[action]()

First I've defined 2 functions (northOfHouse and westOfHouse). Each of this functions will simply print there location and ask for a new input. They will then attempt to call the function for the given input in the dictonary.

Next I define the dictionary, in my case using the keys "WEST" and "NORTH" to reference the correct functions(note that I'm not calling the functions). These can then be called using the appropriate myDict["WEST"]() or myDict["NORTH"]() as you would expect.

Using this it's possible to enter "NORTH" and "WEST" and see the appropriate function being called, this can obviously be expanded to what you want to do (with the inclusion of appropriate input validation and performing these instructions on a loop basis rather than recursively of course as with the code provided, recursion depth errors will haunt you after too long).

Another thing I'd recommend is to return a dictionary from each function, that way the current location determines where you can move to next:

def northOfHouse():
    print "You're in the NORTH of the house\nYou can go 'WEST'"
    myDict = {
        "WEST": westOfHouse
    }
    return myDict

def westOfHouse():
    print "You're in the WEST of the house\nYou can go 'NORTH'"
    myDict = {
        "NORTH": northOfHouse
    }
    return myDict

currentMoves = northOfHouse()
while 1:
    action = raw_input()
    if(action in currentMoves):
        currentMoves = currentMoves[action]()
    else:
        print "Invalid Input"

Try Here on repl.it

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
  • The more I build on this, the more I want to just built it into something huge, but I think classes and nested dictionaries are a bit beyond the scope of this question. – Nick is tired Apr 19 '17 at 15:36
  • Thank you Nick A, That worked. Also, moving the dictionary below my definitions allowed the value northOfhouse to be defined. – Darwin Apr 19 '17 at 16:08
  • @Darwin, I wasn't sure of the structure of the rest of your code but yes that couldve been an issue, dont forget to accept the answer if it solved your problem. – Nick is tired Apr 19 '17 at 16:10