Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make try-except-KeyError shorter in python?

Very often I use the following construction:

try:
    x = d[i]
except KeyError:
    x = '?'

Sometimes, instread of '?' I use 0 or None. I do not like this construction. It is too verbose. Is there a shorter way to do what I do (just in one line). Something like.

x = get(d[i],'?')
like image 534
Roman Avatar asked Jun 07 '13 11:06

Roman


People also ask

How do you shorten a try except in Python?

There is no way to compress a try / except block onto a single line in Python. Also, it is a bad thing not to know whether a variable exists in Python, like you would in some other dynamic languages. The safer way (and the prevailing style) is to set all variables to something.

How do I get rid of KeyError in Python?

How to Fix KeyError in Python. To avoid the KeyError in Python, keys in a dictionary should be checked before using them to retrieve items. This will help ensure that the key exists in the dictionary and is only used if it does, thereby avoiding the KeyError . This can be done using the in keyword.

How do you raise the KeyError exception 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.

How do I fix key errors?

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.


1 Answers

You are looking for this:

x = d.get(i, '?')
like image 115
kirelagin Avatar answered Sep 23 '22 04:09

kirelagin