4

I'm trying to sum values in a dictionary that has strings for keys, and lists as the values.

The standard sum(d.values()) doesn't work.

d= {'a': [6,7,8], 'b':[30,-3, 5000,] 'c':[200.6], 'd':[2,2,2,2,2,2,2]}

When I use the sum(d.values()) I get:

TypeError: unsupported operand type(s) for +: 'int' and 'list'
guyinclass
  • 41
  • 3

7 Answers7

4

You can use sum and map on the dicts's values like this

>>> sum(map(sum, d.values()))
5262.6
Sunitha
  • 11,777
  • 2
  • 20
  • 23
2

The best way is to create a generator that takes the sum of each array, and fianlly finds the sum of the values in the generator.

or if you just want to see the code.

sum(sum(a) for a in d.values())

1

You can unpack the list of lists returned by d.values() as in this question.

sum(y for x in d.values() for y in x)
LeopardShark
  • 3,820
  • 2
  • 19
  • 33
1

You can do a sum() of the sum() of each sublist:

sum(sum(x) for x in d.values())

Or if you don't mind importing a library:

import itertools as it
sum(it.chain(*d.values()))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Good solutions already here, but this is another way

sum(sum(a) for a in d.values())
Deepstop
  • 3,627
  • 2
  • 8
  • 21
  • Or `sum(sum(a) for a in d.values())` which I like so much I changed the answer. Thanks for triggering the memory. – Deepstop Jul 21 '19 at 00:48
1

One version with itertools.chain:

from itertools import chain

d= {'a': [6,7,8], 'b':[30,-3, 5000], 'c':[200.6], 'd':[2,2,2,2,2,2,2]}

print(sum(chain(*d.values())))

Prints:

5262.6
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1

One of the shortest way:-

sum( sum(d.values(), [] ) )

Output

5262.6
Rahul charan
  • 765
  • 7
  • 15