【问题标题】:Checking a list against keys in a dictionary根据字典中的键检查列表
【发布时间】:2021-01-19 17:36:08
【问题描述】:

这里对 python 非常陌生,这个问题似乎与这里提出的其他几个问题相似,但在其他方面有所不同。

我想检查我创建的列表中的字符串是否出现在我创建的字典的键值中。我想使用 for 循环为匹配字典和列表的值打印一条消息,并为列表中但不在字典中的值打印另一条消息。

例如

class_mates = ['Peter','Susan','Jen','Jeff','Niel','Sharon','Adam']

respondents = {
'jeff':'python'
'susan':'ruby'
'niel':'c'
'peter':'python'
}
  1. 我故意将受访者设为小写,因为理想情况下,答案中包含某种使用函数的方法,也许是 lower(),使值不区分大小写。

  2. 我想使用 for 循环,但愿意学习更好的方法。理想情况下,我的输出是这样的,

Thanks for taking the poll Peter.
Thanks for taking the poll Susan.
Hello, Jen. Please take our programming language poll.
Thanks for taking the poll Jeff.
etc.

我试过了

for name, language in respondents.items():
    if name.lower() in respondents.keys() == name.lower() in class_mates:
      print("\nThanks for taking the poll",name.title())
    else:
        print("Hello,",name.title()+". Please take our programming language poll."

每当我运行它时,它只会为受访者中的每个匹配项打印 else 语句。 如果有人能告诉我我做错了什么, 并指出我正确的方向,我将不胜感激。 感谢您的帮助!

【问题讨论】:

    标签: python list dictionary for-loop comparison


    【解决方案1】:

    我想通了。我试图迭代错误的可迭代对象,并试图检查 class_mates 中是否有小写名称,这总是会返回 false。

    【讨论】:

    • 如果问题得到解决,请关闭问题。
    猜你喜欢
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2020-02-06
    相关资源
    最近更新 更多