Question

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

Solution

You are looking for this:

x = d.get(i, '?')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top