Python 忽略 KeyError 并继续程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15653966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:38:33  来源:igfitidea点击:

Ignore KeyError and continue program

pythondictionarypython-3.x

提问by jevans

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.

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

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

Example input: GPG,HNZ,DIL,FRE

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

The output is as follows:

输出如下:

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

AIR,HNZ,AAX,DIL,AZX

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

AAX,AZX字典中不存在(EXCHANGE_DATA)这些术语但这些术语存在的地方AIR,HNZ,DIL。该程序显然会抛出KeyError异常,但我已经用pass. 问题是在执行pass代码后程序退出,我需要它继续并在for上执行循环DIL。我该怎么做呢?

采纳答案by Artsiom Rudzenka

Why not:

为什么不:

 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

OR check dict.get method:

或检查 dict.get 方法:

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

And as @RedBaron mentioned:

正如@RedBaron 提到的:

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

回答by Johannes Overmann

You just need to move the try/exceptblock into the for loop.

您只需要将try/except块移动到 for 循环中。

回答by xuanji

catch the exception in the loop

捕获循环中的异常

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:
        pass

Edit: The more pythonic way would be to test if the dict has the element first

编辑:更pythonic的方法是测试dict是否首先包含元素

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