-1

I have an array of dictionaries that I want to reduce

foo = [{'value': 45}, {'value': 2}, {'value': 3}, {'value': 0}]
reduce(lambda x, y: x['value']+y['value'] , foo)

gives me the following error

TypeError: 'int' object has no attribute '__getitem__'

what I ended up doing was to first create a simple array using a comprehension.

reduce(lambda x, y: x+y, [x['value'] for x in foo])
elewinso
  • 2,453
  • 5
  • 22
  • 27

3 Answers3

3

You are using reduce wrong.

from functools import reduce

foo = [{'value': 45}, {'value': 2}, {'value': 3}, {'value': 0}]
reduce(lambda acc, item: acc + item['value'], foo, 0)

Once reduces list items against an accumulator, not list items against each other.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
3

reduce(function, [a, b, c]) is equivalent to function(function(a, b), c). The result of function must therefore be suitable to act as the first argument of function.

To illustrate, this works:

>>> reduce(lambda x, y: {'value': x['value']+y['value']} , foo)
{'value': 50}
Ruud de Jong
  • 744
  • 3
  • 11
0

If you're trying to sum the integer values

You could just reduce using a builtin from the operator library:

from functools import reduce
from operator import add, itemgetter

reduce(add, map(itemgetter('value'), foo))
Jack Evans
  • 1,697
  • 3
  • 17
  • 33