Roman
Roman

Reputation: 131058

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

Upvotes: 8

Views: 1558

Answers (1)

kirelagin
kirelagin

Reputation: 13616

You are looking for this:

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

Upvotes: 18

Related Questions