【问题标题】:KeyError: Dictionary and InputKeyError:字典和输入
【发布时间】:2021-12-29 20:54:26
【问题描述】:

我收到一个 KeyError。 else 块不起作用。当输入超出字典时,它会不断给出 KeyError,但它应该 print("problem")

如果您知道解决此问题的方法,请告诉我。谢谢。

words = {"good night": ["nighty night", "good night", "sleep well"],
         "good morning": ["good morning", "wakey-wakey!", "rise and shine!"]}

text_punk = input("text something: ")

punk = random.choice(words[text_punk])


if text_punk in words:
    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

【问题讨论】:

  • punk = random.choice(words[text_punk]) 那行代码在 if/else 之前。
  • 你在if条件之前访问它,这就是它应该抛出错误的地方
  • 非常感谢@JohnGordon 和 shriakhilc 的帮助,非常感谢...我快要疯了!

标签: python dictionary random input keyerror


【解决方案1】:

在此代码中,在您检查 if text_punk in words 之前引发了异常:

punk = random.choice(words[text_punk])  # might raise

if text_punk in words:
    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

您可以通过在分配punk 之前检查words 来修复它:

if text_punk in words:
    punk = random.choice(words[text_punk])  # shouldn't raise
    print(punk)
    talk(punk) #this is for pyttsx3
else:
    print("problem!")

或使用try/except 代替if/else

try:
    punk = random.choice(words[text_punk])  # might raise
    print(punk)
    talk(punk) #this is for pyttsx3
except KeyError:
    print("problem!")

【讨论】:

  • 感谢@Samwise 的回答和帮助,非常感谢它确实有效!
猜你喜欢
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多