-2

A list of tuples a like ('foo',1),('bar',2),('foo',2),('bar',3), I want each unique key or a[0] along with a sum of each value or a[1], so: {'foo': 3, 'bar': 5} -- some quick way of doing this w/o itertools?

Wells
  • 10,415
  • 14
  • 55
  • 85
  • 1
    1. Quick compared to what? 2. Why not itertools? – jonrsharpe Jul 10 '16 at 18:25
  • Next time you find yourself writing [python recipe:](http://stackoverflow.com/q/38233057/3001761), cook something yourself first. And note http://meta.stackexchange.com/q/19190/248731 – jonrsharpe Jul 10 '16 at 19:18

1 Answers1

0

The following should do the trick without itertools...

pairs = [('foo',1),('bar',2),('foo',2),('bar',3)]

def sum_pairs(pairs):
  sums = {}
  for pair in pairs:
    sums.setdefault(pair[0], 0)
    sums[pair[0]] += pair[1]
  return sums.items()

print sum_pairs(pairs)
Paul Kenjora
  • 1,914
  • 18
  • 20