Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'reduce' on a list of dictionaries

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?

like image 818
Veer Singh Avatar asked Feb 25 '17 07:02

Veer Singh


People also ask

How do I sort a list of dictionaries by value?

To correctly sort a dictionary by value with the sorted() method, you will have to do the following: pass the dictionary to the sorted() method as the first value. use the items() method on the dictionary to retrieve its keys and values. write a lambda function to get the values retrieved with the item() method.

Can you use list comprehension for dictionaries?

Using dict() method we can convert list comprehension to the dictionary. Here we will pass the list_comprehension like a list of tuple values such that the first value act as a key in the dictionary and the second value act as the value in the dictionary.

Do dictionaries use less memory than lists?

Memory Consumption by dict vs list of tuples. Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly see that there is a huge difference between memory consumption of both the datatypes when both are empty.

How do I remove a dictionary from a list?

To remove a dictionary from a list of dictionaries: Use a list comprehension to iterate over the list. Exclude the matching dictionary from the new list. The list comprehension will return a new list that doesn't contain the specified dictionary.


1 Answers

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

No, the first parameter passed to the lambda (for all calls except the first) is the return value from the previous call to the lambda. Your function returns a number, so it will be called with x being a number, not a dictionary.

There are two ways to deal with this. The probably more straightforward one is:

num_favorites = reduce(lambda x, y: x + y['likes'], msgs, 0)

The 0 is the "initializer" argument to reduce, which provides the first value for x. Now in each call, x is the running sum and y is the next dictionary.

Another way, just to show that it can be done, is:

result = reduce(lambda x, y: { 'likes': x['likes'] + y['likes'] }, msgs)
num_favorites = result['likes']

which makes the return value of the lambda be a dict with a likes key, just like its arguments, so we're working with the same type the whole way through. In this case it's unnecessary and wasteful, but if you were aggregating more than one key, it might be an interesting approach.

like image 180
hobbs Avatar answered Sep 22 '22 14:09

hobbs