title: Group by and aggregate the values of a list of dictionaries in Python
body: <p>I'm trying to write a function, in an elegant way, that will group a list of dictionaries and aggregate (sum) the values of like-keys.</p>
  
  <p><strong>Example:</strong></p>
  
  <pre><code>my_dataset = [  
      {
          'date': datetime.date(2013, 1, 1),
          'id': 99,
          'value1': 10,
          'value2': 10
      },
      {
          'date': datetime.date(2013, 1, 1),
          'id': 98,
          'value1': 10,
          'value2': 10
      },
      {
          'date': datetime.date(2013, 1, 2),
          'id' 99,
          'value1': 10,
          'value2': 10
      }
  ]
  
  group_and_sum_dataset(my_dataset, 'date', ['value1', 'value2'])
  
  """
  Should return:
  [
      {
          'date': datetime.date(2013, 1, 1),
          'value1': 20,
          'value2': 20
      },
      {
          'date': datetime.date(2013, 1, 2),
          'value1': 10,
          'value2': 10
      }
  ]
  """
  </code></pre>
  
  <p>I've tried doing this using itertools for the groupby and summing each like-key value pair, but am missing something here. Here's what my function currently looks like:</p>
  
  <pre><code>def group_and_sum_dataset(dataset, group_by_key, sum_value_keys):
      keyfunc = operator.itemgetter(group_by_key)
      dataset.sort(key=keyfunc)
      new_dataset = []
      for key, index in itertools.groupby(dataset, keyfunc):
          d = {group_by_key: key}
          d.update({k:sum([item[k] for item in index]) for k in sum_value_keys})
          new_dataset.append(d)
      return new_dataset
  </code></pre>