Darwin
Darwin

Reputation: 103

Calling a function in program from a dictionary

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.

Upvotes: 0

Views: 661

Answers (1)

Nick is tired
Nick is tired

Reputation: 7055

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

Upvotes: 1

Related Questions