tags:

views:

318

answers:

7

Suppose I have this code in Python:

l = dict['link']
t = dict['title']        <<<<<<<<error here, there is no "title"
d = dict['description']
k = dict['keyword']

What if there is an error on line 2, but I want it to continue running the script and assign the other values? Can I just "ignore" the errors?

EDIT: I know how to do a simple try, except. However, Oftentimes when there is an error on #2, it will shoot to the except, and then NOT continue the rest of the code.'

EDIT: I understand that there is a "get" method. However, I'd like a GENERAL way of doing it...I won't always be using dictionaries.

A: 

Ever heard of Try Catch and exception handling? You can readup on them here

However, you should shy away from causing errors on purpose, why do you have code that you know will fail?

Daniel Goldberg
+7  A: 

The easiest option is to use .get():

l = dict.get('link')
t = dict.get('title')
d = dict.get('description')
k = dict.get('keyword')

The t variable will then contain None (you can use dict.get('title', '') if you want an empty string, for example). Another option would be to catch the KeyError exception.

Lukáš Lalinský
+6  A: 
t = dic.get('title')

won't produce the error. it's equivalent to:

try:
    t = dic['title']
except KeyError:
    t = None

and please don't shadow built-in, don't use dict for a variable name. use something else.

SilentGhost
+1  A: 

In this case, your best bet is to use

l = dict.get('link', 'default')
t = dict.get('title', 'default')

etc.

Any values that weren't in the dictionary will be set to 'default' (or whatever you choose). Of course, you'll have to deal with this later...

Peter
A: 

Try/except/finally; see the tutorial

However, the main question is; why are you assigning these to variables in the first place instead of accessing the dictionary?

Kimvais
A: 

Use exceptions

try:
    l = dict['link']
    t = dict['title']  
    d = dict['description']
    k = dict['keyword']
except (RuntimeError, TypeError, NameError):
    print ('something')
bua
A: 

If you want a way to consume exceptions and continue (though this is probably not a good idea) you could use a wrapper function such as:

def consume_exception(func, args, exception):
    try:
        return func(*args)
    except exception:
        return None

Or something like that.

Then call

l = consume_exception(dict.__getitem__, ['link'], KeyError)
t = consume_exception(dict.__getitem__, ['title'], KeyError)
...
JonahSan