Ignore KeyError and continue the program

In Python 3, I have a program encoded as shown below. It mainly receives data from the user and checks it for the dictionary (EXCHANGE_DATA) and displays 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 

Input Example: 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

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

+4
source share
3 answers

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 the dict.get method:

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

And as @RedBaron said:

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

catch exception in 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 larger the pythonic way will check if the dict element has the first

 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) 
+4
source

You just need to move the try / except block to the for loop.

+1
source

All Articles