title: Python: is "except KeyError" faster than "if key in dict"?
body: <p>Edit 2: It was suggested that this is a copy of a similar question. I'd disagree since my question focuses on speed, while the other question asks what is more &quot;readable&quot; or &quot;better&quot; (without defining better). While the questions are similar, there is a big difference in the discussion/answers given.</p>
  <blockquote>
  <p>EDIT:
  I realise from the questions that I could have been clearer.
  Sorry for code typos, yes it should be using the proper python operator for addition.</p>
  <p>Regarding the input data, I just chose a list of random numbers since that's a common sample. In my case I'm using a dict where I expect a lot of keyerrors, probably 95% of the keys will not exist, and the few that exist will contain clusters of data.</p>
  <p>I'm interested in a general discussion though, regardless of the input data set, but of course samples with running times are interesting.</p>
  </blockquote>
  <p>My standard approach would be like so many other posts to write something like</p>
  <pre><code>list =  (100 random numbers)
  d = {}
  for x in list:
      if x in d:
          d[x]+=1
      else:
          d[x]=1
  </code></pre>
  <p>But I just came to think of this being faster, since we dont have to check if the dictionary contains the key. We just assume it does, and if not, we handle that.
  Is there any difference or is Python smarter than I am?</p>
  <pre><code>list =  (100 random numbers)
  d = {}
  for x in list:
      try:
          d[x]+=1
      except KeyError:
          d[x] = 1
  </code></pre>
  <p>The same approach with indexes in an array, out of bounds, negative indexes etc.</p>