我正在尝试检查用户给出的单词是否是我字典中的关键字,但响应总是转到'else‘部分。
这是我的dic:
mydic = {'Paris':[132,34] 'Rome':[42,35] 'San Remo':[23,66]}
代码如下:
my_input = input('Write a command').lower()
useful_input = my_input.split()
if my_input == 'info':
print("Write 'city' and city name to get the info")
elif their_command == 'city' and phrase:
if phrase in mydic.keys():
print(f"{phrase} city has {mydic.get(phrase)[0]} churches.")
else:
print('Wrong')
因此,我需要搜索单词“city”之后的第二个单词(或第二个和第三个单词)是否是我的字典中的关键字。如果是,我需要在print语句中返回键的第一个值。在我的代码中,它直接指向'else‘并输出'wrong',那么为什么会发生这种情况呢?
发布于 2021-04-24 21:39:28
您可以将输入转换为小写。
你的钥匙是大小写混合的。
顺便说一句,你可以写phrase in mydic
,你不需要得到键的列表。您可以在字典中查找mydic[phrase]
。该方法与get
之间的唯一区别是处理不存在的条目。
发布于 2021-04-24 21:48:31
我想是因为你的输入是低调的。尝试下面的代码
mydic = {'Paris':[132,34], 'Rome':[42,35], 'San Remo':[23,66]}
my_input = input('Write a command: ')
useful_input = my_input.split()
their_command = useful_input[0]
words = useful_input[1:]
phrase = " ".join(words)
if my_input.lower() == 'info':
print("Write 'city' and city name to get the info")
elif their_command.lower() == 'city' and phrase:
if phrase in mydic.keys():
print(f"{phrase} city has {mydic.get(phrase)[0]} churches.")
else:
print('Wrong')
发布于 2021-04-24 22:47:13
phrase =连接的第二个和第三个参数(来自代码phrase =‘’.join(Word)的第一个示例),因此如果您在输入中键入'city Paris Rome‘
在线
if phrase in mydic.keys():
Python将比较字典的键值中是否有parisrome,该值始终为false至少在mydic中有parisrome city
我的建议不是连接字符串,而是使用useful_input列表中的项目迭代抛出字典
令人惊叹的例子,迭代抛出字典你可以在这里找到Iterating over dictionaries using 'for' loops
https://stackoverflow.com/questions/67243390
复制相似问题