【问题标题】:Small if-else issue python小if-else问题python
【发布时间】:2026-01-22 05:35:02
【问题描述】:
   dct = {1:'James', 2:'Alex', 3:'Thomas'}
   if dct == 'James':
       print('There is a James in the dictionary.')
   else:
       print("There is no James.")

我似乎无法弄清楚为什么这个 if-else 语句不起作用,我知道它很小,但我一直得到错误的输出。有谁知道为什么?我的字典有问题吗?感谢您的帮助!

【问题讨论】:

  • {1:'James', 2:'Alex', 3:'Thomas'}'James' 不同。

标签: python-3.x


【解决方案1】:

你需要这样的东西:

dct = {1:'James', 2:'Alex', 3:'Thomas'}
if 'James' in dct.values():
    print('There is a James in the dictionary.')
else:
    print("There is no James.")
  1. 您需要in 运算符来比较'James'
  2. 您需要以某种方式迭代您的 dict 的值,因此使用 .values() 获取列表并使用 in 就像我在 1. 中所说的那样是最简单和最简洁的方法。

【讨论】:

  • 谢谢,正是我需要的!我刚开始使用字典,所以我一直在尝试使用它们的基本功能,学习字典的所有用法仍在进行中。
  • 别担心,我们都去过那里!坚持下去,我们都需要改进。很高兴我能帮上忙!不过可以肯定的是,您了解我的答案背后的机制吗?如果您有任何问题,请不要犹豫。
  • @BlakeMcLaughlin 请记住,如果您要对 values 进行 in 检查,则这些值应该是键,否则您将无法达到目的字典,这是高效的常数时间查找。
  • @cᴏʟᴅsᴘᴇᴇᴅ 如果我理解正确,我完全同意你的看法。如果他不需要字典结构,他可以使用列表。但如果不是这就是我将如何实现它。