【问题标题】:display a dictionary value using input使用输入显示字典值
【发布时间】:2016-07-13 14:19:49
【问题描述】:

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

输入首先被转换为低级,然后拆分成单个单词以在字典中引用。

# 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']
             }

【问题讨论】:

  • problem1是什么?
  • 嗨,我不明白你的问题。能详细点吗?
  • 好的,所以代码问了 3 个问题,第三个问题是一个输入,询问您的设备有什么问题(问题 1 是那个输入)然后我将它设置为将所有文本从输入转换为小写并将其拆分,以便我可以将输入中的单词与字典中的键进行比较并生成答案示例:用户输入我弄湿了。然后程序从句子中查找与字典中的键匹配的单词,即单词“wet”并输出键值。

标签: python dictionary input


【解决方案1】:

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

【讨论】:

  • 我完全同意您的回答,但发现 OP 说他们收到了所有字典值的输出很奇怪。我对此感到非常困惑,想知道原始列表“问题列表”的值是什么
  • 输入首先被转换为低级,然后拆分成单个单词以在字典中引用。 @Eoins 有时可能无法连贯地表达他们的问题.查看 OP 使用的数据结构可以提供一个解决方案,将它们置于正确的方向。感谢您的观察。
  • 谢谢你,Moses 这几天一直在绞尽脑汁,我是 python 新手,我正在努力学习它以帮助我女儿在学校学习它。
  • 哦,可爱。然后你会发现SOpython的What tutorial should I read?很有用
  • opps 好的,如果我在输入中输入 1 个单词,例如湿,它可以工作,但如果我输入我弄湿了它就找不到解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多