Python adding dictionary values with same key within a list -


i picked python not long ago.

an example below

i have dictionary within list

myword = [{'a': 2},{'b':3},{'c':4},{'a':1}] 

i need change output below

[{'a':3} , {'b':3} , {'c':4}] 

is there way can add value together? tried using counter, prints out each dict out.

what did using counter:

for in range(1,4,1):       text = myword[i]       print counter(text) 

the output

counter({'a': 2}) counter({'b': 3}) counter({'c': 4}) counter({'a': 1}) 

i have read link below compared between 2 dict.

is there better way compare dictionary values

thanks!

merge dictionaries 1 dictionary (counter), , split them.

>>> collections import counter >>> myword = [{'a': 2}, {'b':3}, {'c':4}, {'a':1}] >>> c = counter() >>> d in myword: ...     c.update(d) ... >>> [{key: value} key, value in c.items()] [{'a': 3}, {'c': 4}, {'b': 3}]  >>> [{key: value} key, value in sorted(c.items())] [{'a': 3}, {'b': 3}, {'c': 4}] 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -