title: Check if key exists and get the value at the same time in Python?
body: <p>Sometimes we may need to verify the existence of a key in a dictionary and make something if the corresponding value exists.</p>
  
  <p>Usually, I proceed in this way:</p>
  
  <pre><code>if key in my_dict:
      value = my_dict[key]
      # Do something
  </code></pre>
  
  <p>This is of course highly readable and quick, but from a logical point of view, it bothers me because the same action is performed twice in succession. It's a waste of time.</p>
  
  <p>Of course, access to the value in the dictionary is amortized and is normally instantaneous. But what if this is not the case, and that we need to repeat it many times?</p>
  
  <p>The first workaround I thought to was to use <code>.get()</code> and check if the returned value is not the default one.</p>
  
  <pre><code>value = my_dict.get(key, default=None)
  if value is not None:
      # Do Something
  </code></pre>
  
  <p>Unfortunately, this is not very practical and it can cause problems if the key exists and its corresponding value is precisely <code>None</code>.</p>
  
  <p>Another approach would be to use a <code>try</code> / <code>except</code> block.</p>
  
  <pre><code>try:
      value = my_dict[key]
      # Do something
  except KeyError:
      pass
  </code></pre>
  
  <p>However, I highly doubt this is the best of ways.</p>
  
  <p>Is there any other solution which is unknown to me, or should I continue using the traditional method?</p>