In this exercise, we will be focussing on the benefits of using reduce() and map() together.

Consider the example of having a dictionary representing a cost of an item sale called costs which maps an item name to a tuple containing the total number of units sold and the price per unit. A dictionary entry would look like this:

"name": (total_number_of_item_sold, price_per_item)

We wish to find the total cost of all items sold. If this were a list or a tuple, we could simply apply reduce() on it to find the sum. This, however, would present a problem if we attempt this with a dictionary.

The lambda provided to reduce() requires that the two parameters and the returned value be of the same type. For example, in the lambda lambda x, y: x*y, the x, y, and return type are all integers. As you can see, you cannot directly reduce a dictionary to a number because they are not of the same type; we must process the data in the dictionary first.

We can use map() to iterate through the dictionary and compute the cost of every item sold. We can potentially store this in a tuple and then reduce that tuple to a single number, the total cost.

Note: when passing a dictionary as an iterable, the function will iterate through the list of the dictionaries keys.

Let’s look at an example with the following program:

from functools import reduce # Dictionary entry: {"name: (number_or_units_sold, price_per_unit_GBP)} costs = {"shirt": (4, 13.00), "shoes":(2, 80.00), "pants":(3, 100.00), "socks":(5, 5.00)} k = reduce(lambda x, y: x+y, map(lambda q: costs[q][0] * costs[q][1], costs)) print(k) # Output will be a total cost of: 537.0 GBP

This dictionary is passed into map() along with the lambda lambda q: costs[q][0] * costs[q][1]. The lambda function takes the price tuple and generates a total_cost_per_item by multiplying the number_of_units_sold (costs[q][0]) by the price_per_unit_GBP (costs[q][1]). The lambda in the reduce() function is now working strictly with integers to sum them up and returns a total cost of £537.

We could have done this exercise using namedtuple, but we excluded it for brevity. Using map() to process a dictionary is key when working with the JSON format, as we will see in a later exercise.



The dictionary provided represents the number of a given fruit sold over three days - a dictionary entry is:

fruit_name:(amount sold on day 1, amount sold on day 2, amount sold on day 3)

Using map() and reduce(), find the total number of fruits sold. Store this answer in a variable called total_fruits. Make sure to print out your solution.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?