返回键值后如何修复Python dict.get() returns默认值?

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

当我尝试输入例如"help move" 此代码将相应的帮助消息打印到 "move" 和默认值。但是如果我理解 dict.get(key[ value]) 是正确的,默认值应该只有在键(例如 "run" 而不是 "move")不在字典中时才会出现。

我已经尝试检查我的密钥是否为字符串并且没有空格。不知道其他什么/如何检查。

#!/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.")

如果我输入 help move,我期望输出 This is a special help text.,但实际输出是 This is special help text. Sorry, I cannot help you with "move".

问题的关键在于这一行:

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

您的默认值在调用 get 之外,因此它不是默认值,而是被串联起来。要使其成为默认值,请修改为:

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