-2

I have in my code a list with multiple dictionaries in it (at the moment I have a specific number of dictionaries, but I need the program to work for any n numbers of dictionaries).

For example, let say I have 3 dictionaries to simplify:

What I have:

my_list = [{'a': 1, 'b': 2, 'c': 3}, {'b':4, 'c': 5, 'd': 6}, {'c':7, 'd': 8, 'e': 9}]

what I need:

my_list = [{'a': 1, 'b': 6, 'c': 15, 'd': 14, 'e': 9}]

or

my_list = {'a': 1, 'b': 6, 'c': 15, 'd': 14, 'e': 9}

(It's essentially the same thing, isn't it?)

Thank you for your help!!!

amam3214
  • 1
  • 2
  • 1
    Possible duplicate of [merging several python dictionaries](https://stackoverflow.com/questions/9415785/merging-several-python-dictionaries) – Woot4Moo Jul 27 '18 at 20:27
  • @Woot4Moo This doesn't answer my question because in the thread that you linked the values doesn't add up together – amam3214 Jul 28 '18 at 09:14

1 Answers1

3

Use sum() and collections.Counter:

In [90]: sum(map(Counter, my_list), Counter())
Out[90]: Counter({'a': 1, 'b': 6, 'c': 15, 'd': 14, 'e': 9})

Also read https://stackoverflow.com/a/42717000/2867928 for more information.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Hey there, thanks for your answer, But you see, I am quite a newbie and I don't quite understand these `In [90]` and `Out[90]` . Forgive my ignorance but could you please elaborate? – amam3214 Jul 27 '18 at 20:45
  • @amam3214 Read the link that I've posted and the documentation for `sum` and `map` functions. https://docs.python.org/3/library/functions.html – Mazdak Jul 28 '18 at 06:37