Search code examples
pythonexceptionsyntaxtry-catchkeyerror

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],'?')

Solution

  • You are looking for this:

    x = d.get(i, '?')