0

I have a list of elements where each element is a type of dictionary. I want this implementation to be done in Python.

My input is like this:

MyList = [{'Kathy':1, 'Bob':1, 'Spencer':1}, {'Kathy':4, 'Cynthia':2, 'Bob':3, 'Goldman':1}, {'Spencer':2, 'Bob':1}]

My output should be like this:

MyDict = {'Kathy':5, 'Bob':5, 'Spencer':3, 'Cynthia':2, 'Goldman':1}
Trinimon
  • 13,839
  • 9
  • 44
  • 60
zizouraj
  • 473
  • 2
  • 11
  • 1
    possible duplicate of [Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?](http://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe) – Pavel Anossov Apr 23 '13 at 19:50

3 Answers3

2

Use a Counter:

>>> from collections import Counter
>>> myList = [{'Kathy':1, 'Bob':1, 'Spencer':1}, {'Kathy':4, 'Cynthia':2, 'Bob':3, 'Goldman':1}, {'Spencer':2, 'Bob':1}]
>>> myDict = Counter()
>>> for d in myList:
        myDict.update(d)
>>> myDict
Counter({'Kathy': 5, 'Bob': 5, 'Spencer': 3, 'Cynthia': 2, 'Goldman': 1})
poke
  • 369,085
  • 72
  • 557
  • 602
0

Here's one way to do it using defaultdict.

import collections

MyDict = collections.defaultdict(int)
for d in MyList:
    for k,v in d.items():
        MyDict[k] += v
MyDict = dict(MyDict) #if you want a normal dict

Edit: Looks like the Counter version is nicer. But it's still important to know about defaultdicts in case you ever have to do something other than adding ints. They're useful for accumulating lists or sets for instance.

Antimony
  • 37,781
  • 10
  • 100
  • 107
-1

Here is another way of doing this, what seems to me a little more pythonic than the alternatives offered so far (but it will more likely use more memory, since it is not based on a generator):

my_dict = {key: 0
           for one_dict in list_of_dicts
           for key in one_dict.keys()}
my_dict = {key: one_dict[key]+my_dict[key]
           for one_dict in list_of_dicts
           for key in one_dict.keys()}

Edit: Thanks @ShadowRanger by the insight, however, in this case I would rather use the .keys() option to recover the key specifically, and not simply iterate over every key-pair in the dict, because the key will be needed to add such key to the final dictionaries.

  • Your comprehension is backwards; you need to have the iteration over `list_of_dicts` first, so you have a `one_dict` to iterate second. Also, this won't sum any values, just keep the last value seen, and using `.keys()` in Python 2 is wasteful, while gaining nothing (it makes an intermediate `list` copy of the keys, when you could iterate the `dict` directly with no intermediate `list`). – ShadowRanger Jan 28 '16 at 13:26