title: Python: count occurrences in a list using dict comprehension/generator
body: <p>I want to write some tests to analyse the efficiency of different operations in python, namely a comparison of dictionary comprehensions and dict generators.</p>
  
  <p>To test this out, I thought I would try a simple example: count the number of words in a list using dictionaries.</p>
  
  <p>Now I know that you can do this using <code>collections.Counter</code> (as per an answer here: <a href="https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python">How can I count the occurrences of a list item in Python?</a>), but my objective was to test performance an memory.</p>
  
  <p>One "long-hand" way is to do it in a basic loop.</p>
  
  <pre><code>from pprint import pprint
  
  # Read in some text to create example data
  with open('text.txt') as f:
      words = f.read().split()
  
  dict1 = {}
  for w in words:
      if not dict1.get(w):
          dict1[w] = 1
      else:
          dict1[w] += 1
  pprint(dict1)
  </code></pre>
  
  <p>The result:</p>
  
  <pre><code>{'a': 62,
   'aback': 1,
   'able': 1,
   'abolished': 2,
   'about': 6,
   'accept': 1,
   'accepted': 1,
   'accord': 1,
   'according': 1,
   'across': 1,
   ...
  </code></pre>
  
  <p>Then I got a bit stuck trying to do the same in a dictionary comprehension:</p>
  
  <pre><code>dict2  = { w: 1 if not dict2.get(w) else dict2.get(w) + 1
              for w in words }
  </code></pre>
  
  <p>I got an error:</p>
  
  <pre><code>NameError: global name 'dict2' is not defined
  </code></pre>
  
  <p>I tried defining the dict up front:</p>
  
  <pre><code>dict2 = {}
  dict2  = { w: 1 if not dict2.get(w) else dict2.get(w) + 1
              for w in words }
  pprint(dict2)
  </code></pre>
  
  <p>But of course the counts are all set to 1:</p>
  
  <pre><code>{'a': 1,
   'aback': 1,
   'able': 1,
   'abolished': 1,
   'about': 1,
   'accept': 1,
   'accepted': 1,
   'accord': 1,
   'according': 1,
   'across': 1,
   ...
  </code></pre>
  
  <p>I had a similar problem with dict comprehension:</p>
  
  <pre><code>dict3 = dict( (w, 1 if not dict2.get(w) else dict2.get(w) + 1)
                  for w in words)
  </code></pre>
  
  <p>So my question is: how can I use a dictionary comprehension/generator most efficiently to count the number of occurrences in a list?</p>
  
  <p><em>Update</em>: @Rawing suggested an alternative approach <code>{word:words.count(word) for word in set(words)}</code> but that would circumvent the mechanism I am trying to test.</p>