Home > Software design >  Having issues with functions being called when dictionary is used as a switch/case statement
Having issues with functions being called when dictionary is used as a switch/case statement

Time:02-18

So I'm trying to use a dictionary as a makeshift switch/case statement (Python3.8); But the issue I'm having is that the dictionary runs every function inside of it instead of matching it to the key passed.

This is a code sample:

# function blocks
def USA():
    print "System is in USA\n"
    return "USA"

def UK():
    print "System is in the UK\n"
    return "UK"

def RUS():
    print "System is in RUS\n"
    return "RUS"

def JAP():
    print "System is in JAP\n"
    return "JAP"


def location(local):
    return {'USA' : USA(),
            'UK' : UK(),
            'RUS' : RUS(),
            'JAP' : JAP(),
           }[local]


local = "USA"
country = location(local)

but what get's returned is:

"System is in USA"
"System is in the UK"
"System is in RUS"
"System is in JAP"

So there's clearly some matching issues going on & every function is being called; which pushed me to trying various different variations including:

def location(local):
    return {'USA' : USA(),
            'UK' : UK(),
            'RUS' : RUS(),
            'JAP' : JAP(),
           }.get(local, "NA")

Where I attempt to use .get() to find the correct dictionary item. But to no avail — I can't seem to figure out why it's not matching correctly and how to resolve this.

CodePudding user response:

When you declare the dictionary:

{'USA' : USA(),
            'UK' : UK(),
            'RUS' : RUS(),
            'JAP' : JAP(),
        }

Notice that the functions have parentheses (). This means that when you create the dictionary, you are calling the functions. You should do

func_dict = {'USA' : USA,
            'UK' : UK,
            'RUS' : RUS,
            'JAP' : JAP,
        }

and then

func_dict[local]()

which only calls the function corresponding to local.

  • Related