Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore KeyError and continue program

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

Example input: 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. 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?

like image 491
jevans Avatar asked Mar 27 '13 07:03

jevans


People also ask

How do I ignore KeyError?

Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.

How do I fix KeyError in Python?

How to Fix the KeyError in Python Using the in Keyword. We can use the in keyword to check if an item exists in a dictionary. Using an if...else statement, we return the item if it exists or return a message to the user to notify them that the item could not be found.

How do you handle KeyError?

The Usual Solution: . get() If the KeyError is raised from a failed dictionary key lookup in your own code, you can use . get() to return either the value found at the specified key or a default value.

Why am I getting a KeyError in Python?

A Python KeyError is raised when you try to access an item in a dictionary that does not exist. You can fix this error by modifying your program to select an item from a dictionary that does exist. Or you can handle this error by checking if a key exists first.


2 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 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 mentioned:

 for code in portfolio_list:
     if code in EXCHANGE_DATA:
         print('{:<6} {:<20} {:>8.2f}'.format(code, *EXCHANGE_DATA[code])   
like image 94
Artsiom Rudzenka Avatar answered Sep 20 '22 19:09

Artsiom Rudzenka


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

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)   
like image 31
xuanji Avatar answered Sep 24 '22 19:09

xuanji