Python how to use "try:" not stop when it raises except
<p>I have this code and would like to shorten it. Is this anyway possible? Does not make that much sense to have that often the same code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>try:
  years = values['year']
except KeyError:
  pass

try:
  tracks = values['track']
except KeyError:
  pass

try:
  statuses = values['status']
except KeyError:
  pass
        </code></pre>
</div>
</div>
</p>

<p>How about avoiding the exceptions entirely?</p>

<p><code>.get()</code> allows you to provide a default value if they key doesn't exist already...</p>

<pre><code>years = values.get('year')  # Implicitly default to None
tracks = values.get('track', None)  # Explicitly default to None
statuses = values.get('status', 'Unknown')  # Or use any custom value
</code></pre>

<p>As mentioned in comments by <a href="http://stackoverflow.com/users/487339/dsm">@DSM</a>, this differs from your code in that it guarantees all variables will be bound with <em>some</em> value. Otherwise, attempting to use any of the variables might result in a <code>NameError</code> at run time.</p>

<p>Less efficient, but you can also explicitly check if a key exists...</p>

<pre><code>if 'year' in values:
    # do something
</code></pre>

python optimization