NitroReload
NitroReload

Reputation: 49

Python adding dictionary values with same key within a list

i just picked up python not too long ago.

An example below

i have a dictionary within a list

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

I need to change it to the output below

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

is there a way where i can add the value together? I tried using counter, but it prints out the each dict out.

what i did using Counter:

for i 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 the link below but what they compared was between 2 dict.

Is there a better way to compare dictionary values

Thanks!

Upvotes: 2

Views: 4046

Answers (1)

falsetru
falsetru

Reputation: 369054

Merge dictionaries into one dictionary (Counter), and split them.

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

>>> [{key: value} for key, value in sorted(c.items())]
[{'a': 3}, {'b': 3}, {'c': 4}]

Upvotes: 2

Related Questions