title: How to check for a key in a defaultdict without updating the dictionary (Python)?
body: <p>I usually use the following idiom when working with a Python dictionary:</p>
  
  <pre><code>try:
      val = dct[key]
  except KeyError:
      print key, " is not valid"
  </code></pre>
  
  <p>since for large dictionaries, the statement</p>
  
  <pre><code>if key in dct:
      # do something
  </code></pre>
  
  <p>is not very efficient (so I remember reading, but I've noticed it in practice as well)</p>
  
  <p>Today I was working with a defaultdict and for a moment I forgot that a defaultdict will never give you a KeyError but instead will update the original dictionary.</p>
  
  <p>How can I perform a lookup without updating the defaultdict? I really need to print an error so that the user can reenter the key.</p>
  
  <p>Thank you!</p>
  
  <p><strong>UPDATE:</strong> Several posters suggested that my belief that <code>if key in dct:</code> is slow is false. I went back and checked the book in which I had read that is better to use <code>try: except:</code>. It is 2002's Python Cookbook, Recipe 1.4 by Alex Martelli, which can be found also online here: <a href="http://code.activestate.com/recipes/66516-add-an-entry-to-a-dictionary-unless-the-entry-is-a/" rel="noreferrer">Add an entry to dictionary</a>. Old memories are so unreliable! The recipe doesn't mention "slower" and it's not even using <code>in</code> but <code>has_key</code>. It simply says that <code>try: except:</code> is more Pythonic (at least the book version of the recipe). Thanks for the correction and the answers.</p>