0

I have a bunch of dicts such as ...

{u'APPLES': 1}
{u'PEARS': 7}
{u'BANANAS': 10}

{u'APPLES': 9}
{u'PEARS': 13}
{u'BANANAS': 20}

However I want to add them together so i end up with {"APPLES":10} etc. What is the best pythonic way to do this.

Thanks,

felix001
  • 13,941
  • 29
  • 86
  • 111
  • What form is the data in? Is it `{u'APPLES': 1, u'PEARS': 7, ... }` or `[{u'APPLES': 1}, {u'PEARS': 7}, ... ]`? – Joel Cornett Aug 08 '13 at 21:13
  • It's a little disappointing that the OP on that question chose the answer he did rather than DiggyF's answer (which is identical to mine… and even has the unnecessary `reduce` alternative), but yeah, it's a dup. – abarnert Aug 08 '13 at 21:19

2 Answers2

2
from collections import Counter

counts = Counter()

for d in bunch_of_dicts:
    counts.update(d)
Maciej Gol
  • 14,616
  • 4
  • 32
  • 49
2
import collections

totals = collections.Counter()
for d in a_bunch_of_dicts:
    totals.update(d)
abarnert
  • 334,953
  • 41
  • 559
  • 636
  • I'm surprised it's been 2 minutes and there's still nobody suggesting `reduce` leading to an argument about whether every `reduce` is better as an explicit loop or not. :) – abarnert Aug 08 '13 at 21:16