在字典中搜索用户输入

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

我的功能是从网站获取数据并将其写入文本文件。然后转移到字典中,从那里我会要求用户输入一个国家名称,它会返回键和键的值或人均收入。我遇到的问题是我必须搜索字典才能找到输入,如果它与键匹配,那么它将打印该输入和人均收入。如果我应该使用 for 函数或者我的代码最后是否正确,我不是 100% 确定使用什么。

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 与 country name key 相同,则绑定查找。我需要做什么来搜索字典以匹配输入的键,或者我的代码中是否有任何不必要的东西。

哥斯达黎加

更新 2

啊,比较key的时候有个小问题。实际上,您正在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",一旦它变成大写。

希望能帮助到你

更新

正如@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])

希望能帮助到你

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章