使用输入显示字典值

时间:2016-07-13 14:19:49

标签: python dictionary input

我可以成功导入字典,我可以从字典中获取其值的输出,但它显示了所有值,而不是与用户输入匹配的值。

首先将输入转换为低位,然后将其拆分为单词,以便在字典中引用。

# prob_dict : dictionary

# problemlist : input lowercase and split

我搜索过很多帖子,但找不到有效的解决方案。

problemlist = problem1.split()

for problem in range(len(prob_dict)):
    if prob_dict in problemlist:
        solution = []
        solution = (prob_dict[problem])
        print('Your Solution is:', solution)
    else:
        print('could not find a solution')

字典是:

prob_dict = {'wet': ['put in bag of rice to dry out'],
             'screen': ['screen will need to be replaced'],
             'charger': ['purchase new charger for our store']
             }

1 个答案:

答案 0 :(得分:3)

if prob_dict in problemlist几乎不会发生。你不会在字符串列表中找到dict

相反,您应该遍历列表中的项目,并查看字典是否包含项目的键:

problemlist = [p.lower() for p in problem1.split()]

for problem in problemlist:
    if problem in prob_dict:
        print('Your Solution is: ', prob_dict[problem][0])
              #                                        ^ The associated string
        break # remember to break once solution is found
else:
    print('could not find a solution')