I'm trying to write a simple Python function that sums all values that have the key as likes. I'm working with functional programming for this assignment. Thus, I am required to use either a list-comprehension, map
, filter
, or reduce
. In this case, I see reduce as a reasonable option.
def sum_favorites(msgs):
num_favorites = reduce(lambda x, y: x["likes"] + y["likes"], msgs)
return num_favorites
content1 = {"likes": 32, ...}
content2 = {"likes": 8, ...}
content3 = {"likes": 16, ...}
contents = [content1, content2, content3]
print(sum_favorites(contents))
The issue comes to when I actually run the code. I seem to receive something along the lines of: TypeError: 'int' object is not subscriptable. To me, this error makes no sense. If reduce
is truly iterating through the given parameter, then each item passed into the lambda-function should be a dictionary - and each of them definitely has a likes key in them. What is the issue, and what exactly does this Python error mean?