在字典中搜索用户输入

时间:2019-04-16 21:24:40

标签: python dictionary

大家好,所以我在尝试在字典中查找用户输入时遇到问题。

我的功能是从网站获取数据并将其写入文本文件。然后转移到字典中,从那里我将要求用户输入国家/地区名称,它将返回密钥和该密钥的值或人均收入。我遇到的问题是我必须搜索字典以找到输入,如果它与键匹配,则它将打印该键和人均收入。我不能百分百确定应该使用for函数还是最后我的代码正确。

def main():
    import requests
    webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
    data = requests.get(webFile) #connects to the file and gest a response object
    with open("capital.txt",'wb') as f:
        f.write(data.content) #write the data out to a file – wb used since thecontent from the response object is returned as abinary object.
    f.close()
    countryName = {}
    with open('capital.txt','r') as infile:
        for line in infile:
            num,*key,value = line.split()
            key = ' '.join(key)
            countryName[key] = value.upper()
    userInput = input("Enter a country name: ")
    userInput.upper()
    while(userInput != 'stop'):
            #for loop to see if key is in dictionary
        if userInput in countryName:
            #if(userInput == countryName[key]):
                print("The per capita income in",key, "is",countryName[key])
                userInput = input("Enter a country name: ")
main()
    while(userInput != 'stop'):
            #for loop to see if key is in dictionary
        if userInput in countryName:
            #if(userInput == countryName[key]):
                print("The per capita income in",key, "is",countryName[key])
                userInput = input("Enter a country name: ")
main()

这里是问题所在,试图找到userInput是否与国家/地区名称key相同。我该怎么做才能搜索字典以使键与输入相匹配,或者我的代码中是否包含不必要的内容。

1 个答案:

答案 0 :(得分:1)

更新2

啊,比较按键时有一个小问题。实际上,您正在对upper()做一个没有意义的值(一个数字)。 看看这个更新:

import requests
webFile = "https://www.cia.gov/library/publications/the-world-factbook/rankorder/rawdata_2004.txt"
data = requests.get(webFile)
with open("capital.txt",'wb') as f:
  f.write(data.content)
countryName = {}
with open('capital.txt','r') as infile:
  for line in infile:
     num, *key, value = line.split()
     key = ' '.join(key)
     countryName[key.upper()] = value #key.upper() instead of value.upper()
userInput = input("Enter a country name: ").upper()
counter = 0
while not userInput == "STOP": #'STOP' because it's uppercase
   if userInput in countryName:
      print("The per capita income in", userInput, "is", countryName[userInput])
      userInput = input("Enter a country name: ").upper()
   counter += 1
   if counter >= len(countryName): #It couldn't find the country
      userInput = input("Not found. Enter a new country: ").upper()
      counter = 0 #Let's try again

一个小改进:当用户输入不满足if userInput in countryName并且不是“停止”时,计数器将防止无限循环。除此之外,“ stop”条件必须为"STOP"(大写形式)。

希望有帮助

更新

@Barmar指出,另一种可能性是:

countryName = {
   "countryA": "valueA",
   "countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
if userInput in countryName:
   print ("The country is", userInput, "and the value is", countryName[userInput])

一个很好的建议:我认为文件部分与您自己的问题无关,因此,下次尝试将您的问题简化为更直接的问题:)

无论如何,您可以遍历countryName的键,然后与用户输入进行比较。换句话说:

countryName = {
   "countryA": "valueA",
   "countryB": "valueB"
}
userInput = "countryA" #Of course, it can be a user input
for key in countryName.keys():
   if userInput == key: #Got it
      print ("The country is", key, "and the value is", countryName[key])

希望有帮助