【问题标题】:How to fix Python dict.get() returns default value after returning key value?如何修复 Python dict.get() 返回键值后返回默认值?
【发布时间】:2019-08-24 08:07:12
【问题描述】:

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

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

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

【问题讨论】:

    标签: python-3.x string dictionary output default


    【解决方案1】:

    问题的症结在于这一行:

    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)))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      相关资源
      最近更新 更多