سؤال

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],'?')
هل كانت مفيدة؟

المحلول

You are looking for this:

x = d.get(i, '?')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top