Search code examples
python-3.xstringdictionaryoutputdefault

How to fix Python dict.get() returns default value after returning key value?


When i try to input e.g. "help move" this code prints the corresponding help message to "move" and the default value. But if I understand dict.get(key[, value]) right, the default value should only come up if the key (e.g. "run" instead of "move") is not in the dictionary.

I've tried to check if my key is a string and has no whitespace. Don't know what / how to check else.

#!/usr/bin/env python3
def show_help(*args):
    if not args:
        print('This is a simple help text.')
    else:
        a = args[0][0]       
        str_move = 'This is special help text.'

        help_cmd = {"movement" : str_move, "move" : str_move, 
            "go" : str_move}
        #print(a)  # print out the exact string
        #print(type(a))  # to make sure "a" is a string (<class 'str'>)
        print(help_cmd.get(a), 'Sorry, I cannot help you.')

commands = {"help" : show_help, "h" : show_help}

cmd = input("> ").lower().split(" ")  # here comes a small parser for user input
try:
    if len(cmd) > 1:
        commands[cmd[0]](cmd[1:])
    else:
        commands[cmd[0]]()
except KeyError:
    print("Command unkown.")

I excpect the ouput This is a special help text. if I enter help move, but the actual output is This is special help text. Sorry, I cannot help you with "move"..


Solution

  • The crux of the issue is in this line:

    print(help_cmd.get(a), 'Sorry, I cannot help you with "{}".'.format(a))
    

    Your default is outside of the call to get, so it is not acting as a default and is being concatenated. For it to be a default, revise to:

    print(help_cmd.get(a, 'Sorry, I cannot help you with "{}".'.format(a)))