Py学习  »  Python

python决策逻辑与字典中的循环

Kam03 • 4 年前 • 653 次点击  

我目前正忙于为python编写代码。我必须做一个10个单词的python字典,应该提示用户搜索一个单词,程序会搜索这个单词,如果找到匹配的,显示定义。我已经得到了足够的信息,但是我还不能确定是要使用elif,还是为了什么。我需要使用循环,但我卡住了。整天都在这上面。这是我写的代码。

# 1. The user should be prompted for a word to search for.
# 2. The program will then search for the term, and if a match is found, display
# the definition.
# 2. You should demonstrate the following concepts: dictionaries, loops, decision logic, user input, and other concepts you feel are necessary.

x = {"Milwaukee": "Bucks", "Oklahoma": "Thunder" , "Portland": "Trailblazers", "Miami": "Heat" , "Boston" : "Celtics", "New York" : "Knicks" ,  "Orlando" : "Magic" , "Houston" : "Rockets" , "Chicago" : "Bulls" , "Indiana" : "Pacers"} 
team = input("enter team:")
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40043
 
653 次点击  
文章 [ 2 ]  |  最新文章 4 年前
entrez
Reply   •   1 楼
entrez    5 年前

尽管洛奇的答案可能是最简单的方法 要求 您可以使用循环,只需循环遍历字典中的每个项即可手动比较每个项:

team = input('enter team name: ')
for item in x:
  if x[item] == team:
    print(item)

如果需要显示用户是否进入城市或团队的匹配项,只需检查两项:

team = input('enter team or city name: ')
for item in x:
  if x[item] == team:
    print(item)
  elif item == team:
    print(x[item])
Rocky Li
Reply   •   2 楼
Rocky Li    5 年前
team = input('enter team: ')
if team in x:
    print(x[team])
else:
    print('not found')

不需要循环。

我好像搞错了——我以为你会用钥匙找字典,但显然你是想用团队找城市。所以这里是:在一切之前,做这个:

x = {v:k for k, v in x.iteritems()}

这将成为字典 team: city 而不是 city: team 上面的代码仍然有效。