如何将字典值赋值给用户输入定义的变量?Python字典问题求助
Python字典KeyError与返回None的问题
我是编程新手,在使用Python字典时遇到问题,代码多次出现KeyError,即便能运行也会返回“None”或0。以下是我的示例代码:
# Dictionary called choices. choices = { '1.': 'One', '2.': 'Two', '3.': 'Three', } # Display the choices to the user. for k, v in choices.items(): print(f'{k} {v}') # Ask the user to make a choice from the dictionary options. my_choice = int(input('Choose a number 1, 2 or 3: ')) # Make the choice the same as the index[number] of the dictionary my_choice -= 1 # From here I get stuck print(f'You have chosen {choices.get(str(my_choice))}.') # This returns a 0 or None # The desired output is You have chosen Two.
我尝试过for循环、dict.values()、dict.get()、dict.items()以及将my_choice转为字符串等方法,仍无法实现将字典项赋值给my_choice变量,期望输出为“You have chosen Two.”,恳请帮忙解决。
问题根源
你的字典choices的键是'1.'、'2.'、'3.'(带点的字符串),但处理用户输入时:
- 把输入转成整数后减1,比如用户输入2,得到1
- 转成字符串变成
'1',和字典里的'1.'不匹配,所以get()方法找不到对应键,返回默认的None
解决方法
方式一:调整字典键为纯数字字符串
保持显示效果不变,修改字典的键为不带点的数字字符串,和用户输入匹配:
choices = { '1': 'One', '2': 'Two', '3': 'Three', } # 显示选项时加上点,和原效果一致 for k, v in choices.items(): print(f'{k}. {v}') # 直接获取用户输入的字符串,无需转整数再处理 my_choice = input('Choose a number 1, 2 or 3: ') print(f'You have chosen {choices.get(my_choice)}.')
方式二:调整用户输入格式匹配字典键
保留原字典结构,把用户输入的数字转成带点的字符串:
choices = { '1.': 'One', '2.': 'Two', '3.': 'Three', } for k, v in choices.items(): print(f'{k} {v}') my_choice = input('Choose a number 1, 2 or 3: ') # 将输入转为带点的字符串,比如输入2变成'2.' formatted_choice = f'{my_choice}.' print(f'You have chosen {choices.get(formatted_choice)}.')
额外优化:处理无效输入
添加判断逻辑,避免用户输入非1-3的内容时返回None:
choices = { '1': 'One', '2': 'Two', '3': 'Three', } for k, v in choices.items(): print(f'{k}. {v}') my_choice = input('Choose a number 1, 2 or 3: ') if my_choice in choices: print(f'You have chosen {choices[my_choice]}.') else: print('Invalid choice, please enter 1, 2 or 3.')
内容的提问来源于stack exchange,提问作者Zimmie
相关产品推荐
相关产品推荐

