title: Python Generator Expression for Accumulating Dictionary Values
body: <p>A generator expression is throwing off a large number of tuple pairs eg. in list form:</p>
  
  <pre><code>pairs = [(3, 47), (6, 47), (9, 47), (6, 27), (11, 27), (23, 27), (41, 27), (4, 67), (9, 67), (11, 67), (33, 67)]
  </code></pre>
  
  <p>For each pair in pairs, with key = pair[0] and value = pair[1], I want to feed this stream of pairs into a dictionary to cumulatively add the values for the respective keys. The obvious solution is:</p>
  
  <pre><code>dict_k_v = {}
  for pair in pairs:
      try:
          dict_k_v[pair[0]] += pair[1]
      except:
          dict_k_v[pair[0]] = pair[1]
  
  &gt;&gt;&gt; dict_k_v
  {33: 67, 3: 47, 4: 67, 6: 74, 9: 114, 11: 94, 41: 27, 23: 27}
  </code></pre>
  
  <p>However, could this be achieved with a generator expression or some similar construct that doesn't use a for-loop?</p>
  
  <p>EDIT</p>
  
  <p>To clarify, the generator expression is throwing off a large number of tuple pairs:</p>
  
  <p>(3, 47), (6, 47), (9, 47), (6, 27), (11, 27), (23, 27), (41, 27), (4, 67), (9, 67), (11, 67), (33, 67) ...</p>
  
  <p>and I want to accumulate each key-value pair into a dictionary (see Paul McGuire's answer) as each pair is being generated.  The pairs = list[] statement was unnecessary and sorry about that.  For each pair (x,y), x is an integer and y can be an integer or decimal/float. </p>
  
  <p>My generator expression is of the form:</p>
  
  <pre><code>((x,y) for y in something() for x in somethingelse())
  </code></pre>
  
  <p>and want to accumulate each (x,y) pair into a defaultdict.  Hth.</p>