Python根据用户输入匹配多字典值报string indices must be integers错误如何解决
错误原因
错误出在print(first_half[user_error])这行:first_half是从用户输入里截取的首字符字符串(比如输入"A1"时它是字符串"A",不是你定义的字典变量A),字符串类型只能用整数作为索引取值,用字符串"A1"当索引自然会抛出"string indices must be integers"错误。
修正方案
你需要额外建立首字符到对应字典的映射,通过首字符先拿到对应的目标字典,再从字典里取用户输入对应的值,修正后代码如下:
A = { "A1": "something1", "A2": "something2", } B = { "B1": "somethingelse1", "B2": "somethingelse2", } # 新增首字符到字典的映射 dict_map = { "A": A, "B": B } user_error = input("what is your error? ").upper() first_half = user_error[0] # 先通过首字符取到对应字典,再取用户输入对应的值 print(dict_map[first_half][user_error])
如果要兼容输入不存在的场景,避免程序直接报错,可以增加合法性判断:
A = { "A1": "something1", "A2": "something2", } B = { "B1": "somethingelse1", "B2": "somethingelse2", } dict_map = { "A": A, "B": B } user_error = input("what is your error? ").upper() first_half = user_error[0] if first_half in dict_map and user_error in dict_map[first_half]: print(dict_map[first_half][user_error]) else: print("未找到对应内容")
内容的提问来源于stack exchange,提问作者jadechessink
相关产品推荐
相关产品推荐

