【问题标题】:How to make a for loop with exception handling when key not in dictionary?当键不在字典中时如何使用异常处理进行for循环?
【发布时间】:2017-02-01 00:47:49
【问题描述】:

所以,我有一本包含国家名称和相应股票指数的字典。用户被要求输入五个不同的国家,程序获取五个相应的股票指数并对数据进行处理。

当被要求输入时,我检查字典是否可以找到该国家/地区,这种情况发生了五次。现在,处理异常的部分没有做我希望的事情。我的循环和/或异常处理有什么问题??

ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose

countries = []
print('Please choose five stock exchanges to analyse,' )
print('just name the corresponding countries \n')

for i in range(0, 5):
    while True:
        try:
            countr = input('Please enter country no. %d: ' %(i+1))
            countr = countr.title()            
            if countr in ex_dict.keys():
                print('Found the corresponding stock index! \n')
                countries.append(countr)
            break
        except KeyError:
            print('Country not found, please try again! \n')

【问题讨论】:

  • 您希望它做什么,而它又做了什么?
  • 你不需要捕获 KeyError,因为你不会遇到。也使用if countr in ex_dict 而不是if countr in ex_dict.keys()
  • 一个简单的 else 语句而不是捕获 KeyError 将解决您的问题

标签: python for-loop dictionary exception


【解决方案1】:

几点:

  • 您的代码永远不会遇到异常,因为您正在使用 if key in dict.keys() 检查密钥是否存在
  • 此外,还有很多循环。我认为for i in range(0,5) 就足够了。会不那么复杂

    ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
    
    countries = []
    print('Please choose five stock exchanges to analyse,' )
    print('just name the corresponding countries \n')
    
    for i in range(0, 5):
        countr = raw_input('Please enter country no. %d: ' %(i+1))
        countr = countr.title()
        if countr in ex_dict.keys():
            print('Found the corresponding stock index! \n')
            countries.append(countr)
        else:
            print('Country not found, please try again! \n')
    

输出:

C:\Users\dinesh_pundkar\Desktop>python c.py
Please choose five stock exchanges to analyse,
just name the corresponding countries

Please enter country no. 1: USA
Found the corresponding stock index!

Please enter country no. 2: asd
Country not found, please try again!

Please enter country no. 3: asd
Country not found, please try again!

Please enter country no. 4: USA
Found the corresponding stock index!

Please enter country no. 5: United states
Found the corresponding stock index!


C:\Users\dinesh_pundkar\Desktop>

【讨论】:

    【解决方案2】:

    如果股票不在字典 ex_dict 中,我假设你希望它给你一个消息,我已经修改了代码来做同样的事情。

    ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
    
    countries = []
    print('Please choose five stock exchanges to analyse,' )
    print('just name the corresponding countries \n')
    
    for i in range(0, 5):
        while True:
            try:
                countr = input('Please enter country no. %d: ' %(i+1))
                countr = countr.title()            
                if countr not in ex_dict.keys():
                    print ('Try again!')
                else:
                    print('Found the corresponding stock index! \n')
                    countries.append(countr)
    

    【讨论】:

      【解决方案3】:

      来自doc

      每当请求 dict() 对象(使用格式 a = adict[key])并且键不在字典中时,Python 都会引发 KeyError。

      如果您想在用户插入国家/地区字典中不存在的键时打印一条消息,则在您的代码中,您可以简单地添加一个 else 语句而不是 catch 异常。

      您可以通过这种方式更改您的代码:

      if countr in ex_dict.keys():
           print('Found the corresponding stock index! \n')
           countries.append(countr)
           break
      else:
          print('Country not found, please try again! \n')
      

      【讨论】:

        【解决方案4】:

        这里不会有KeyError,因为您的代码永远不会厌倦访问字典,只需检查密钥是否在keys 中。您可以简单地这样做来实现相同的逻辑:

        ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
        
        countries = []
        print('Please choose five stock exchanges to analyse,' )
        print('just name the corresponding countries \n')
        
        for i in range(0, 5):
            while True:
                countr = input('Please enter country no. %d: ' %(i+1))
                countr = countr.title()
                if countr in ex_dict.keys():
                    print('Found the corresponding stock index! \n')
                    countries.append(countr)
                    break
                else:
                    print('Country not found, please try again! \n') 
        

        示例运行:

        Please choose five stock exchanges to analyse,
        just name the corresponding countries 
        
        Please enter country no. 1: sdf
        Country not found, please try again! 
        
        Please enter country no. 1: USA
        Found the corresponding stock index! 
        
        Please enter country no. 2: Aregtng
        Country not found, please try again! 
        
        Please enter country no. 2: Argentina
        Found the corresponding stock index! 
        
        Please enter country no. 3: United States
        Found the corresponding stock index! 
        
        Please enter country no. 4: usa
        Found the corresponding stock index! 
        
        Please enter country no. 5: usa
        Found the corresponding stock index! 
        

        注意:.keys() 太过分了:要检查一个键是否在字典中,你只需要k in some_dict

        【讨论】:

          【解决方案5】:

          您的中断不在 if 范围内...所以它会在第一次尝试时中断。

          【讨论】:

          • 你试过代码了吗?无论有无错误,它都能正常循环。
          • 我的意思是,保证触发的带有中断的 while 循环没有意义。但我承认这没有回答你关于捕获异常的问题......正如其他人所说,代码在尝试countr in ex_dict.keys() 时没有引发任何 KeyError
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-07-03
          • 1970-01-01
          • 1970-01-01
          • 2012-02-07
          • 1970-01-01
          相关资源
          最近更新 更多