title: Efficient Dictionary Searching?
body: <p>I had a quick question about efficiency of searching through <strong>large</strong> dictionaries in Python. I am reading a large comma-separated file and getting a key and value from each line.  If my key is already in the dictionary, I'm adding the value to the value listed in the dictionary, if the key doesn't exist in the dictionary, I simply add the value.  Previously I was using this:</p>
  
  <pre><code>if key in data_dict.keys():
      add values
  else:
      data_dict[key] = value
  </code></pre>
  
  <p>This starts pretty fast, but as the dictionary grows it becomes slower and slower, to the point where I can't use it at all.  I changed the way I search for the key in the dictionary to this:</p>
  
  <pre><code>try:
      # This will fail if key not present
      data_dict[keyStr] = input_data[keyStr] + load_val
  except:
      data_dict[keyStr] = load_val
  </code></pre>
  
  <p>This is infinitely faster, and can read / write over 350,000 lines of code in 3 seconds.</p>
  
  <p>My question was why does the <code>if key in data_dict.keys():</code> command take sooo much longer than the call to <code>try: data_dict[keyStr]</code>?  And why wouldn't Python utilize the <code>try</code> statement when searching for a key in a dictionary?</p>