本文介绍了忽略KeyError并继续执行程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中,我有一个编码如下的程序.它基本上从用户那里获取输入,并对照字典(EXCHANGE_DATA)进行检查,并输出信息列表.

In Python 3 I have a program coded as below. It basically takes an input from a user and checks it against a dictionary (EXCHANGE_DATA) and outputs a list of information.

from shares import EXCHANGE_DATA
portfolio_str=input("Please list portfolio: ")
portfolio_str= portfolio_str.replace(' ','')
portfolio_str= portfolio_str.upper()
portfolio_list= portfolio_str.split(',')
print()
print('{:<6} {:<20} {:>8}'.format('Code', 'Name', 'Price'))
EXCHANGE_DATA = {code:(share_name,share_value) for code, share_name, share_value in EXCHANGE_DATA}
try:
     for code in portfolio_list:
              share_name, share_value = EXCHANGE_DATA[code]
              print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value))
except KeyError:
     pass

示例输入: GPG,HNZ,DIL,FRE

输出如下:

Please list portfolio: GPG,HNZ,DIL,FRE

Code  Name                   Price
GPG   Guinnesspeat            2.32
HNZ   Heartland Nz            3.85
DIL   Diligent                5.30
FRE   Freightway              6.71

但是如果我有这样的输入:

But if I have an input like:

AIR,HNZ,AAX,DIL,AZX

其中术语 AAX,AZX 在字典(EXCHANGE_DATA)中不存在,而术语 AIR,HNZ,DIL 却存在.该程序显然会引发 KeyError 异常,但我已通过 pass 中和了此异常.问题是执行 pass 代码后,程序退出,我需要它继续并在 DIL 上执行 for 循环.我该怎么做?

where the terms AAX,AZX do not exist in the dictionary (EXCHANGE_DATA) but the terms AIR,HNZ,DIL do. The program obviously would throw a KeyError exception but I have neutralized this with pass. The problem is after the pass code has been executed the program exits and I need it to continue on and execute the for loop on DIL. How do I do this?

推荐答案

为什么不呢?

 for code in portfolio_list:
     try:
         share_name, share_value = EXCHANGE_DATA[code]
         print('{:<6} {:<20} {:>8.2f}'.format(code, share_name, share_value)
     except KeyError:
         continue

或检查dict.get方法:

OR check dict.get method:

 for code in portfolio_list:
     res = EXCHANGE_DATA.get(code, None)
     if res:
         print('{:<6} {:<20} {:>8.2f}'.format(code, *res)

正如@RedBaron所述:

And as @RedBaron mentioned:

 for code in portfolio_list:
     if code in EXCHANGE_DATA:
         print('{:<6} {:<20} {:>8.2f}'.format(code, *EXCHANGE_DATA[code])

这篇关于忽略KeyError并继续执行程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 16:16