We need to analyze the sales data from multiple stores. The data consists of tuples containing the store ID, the product name, and the quantity sold. We want to sum up the total quantity sold per product across all stores and then display the products sorted by the total quantity sold in descending order.
from collections import defaultdict
# Sample data: list of tuples (store_id, product_name, quantity)
sales_data = [
(101, 'Apple', 24),
(102, 'Banana', 18),
(103, 'Apple', 32),
(104, 'Orange', 15),
(101, 'Banana', 22),
(103, 'Banana', 30),
(102, 'Apple', 18),
(104, 'Banana', 5),
(101, 'Orange', 12)
]
# Step 1: Aggregate the quantities sold per product
product_totals = defaultdict(int)
for _, product, quantity in sales_data:
product_totals += quantity
# Step 2: Sort the products by total quantity sold in descending order
sorted_products = sorted(product_totals.items(), key=lambda item: item[1], reverse=True)
# Step 3: Display the results
for product, total in sorted_products:
print(f"{product}: {total}")
sales_data. Each tuple contains three elements: store_id, product_name, and quantity.product_totals is initialized as a defaultdict of type int from the collections module. This dictionary will store the total quantity sold for each product.sales_data. The loop uses tuple unpacking to extract the store ID, product name, and quantity directly into variables _, product, and quantity. The underscore _ is used as a placeholder for the store ID, which we don’t need in further calculations.product_totals. The defaultdict takes care of initializing the quantity to zero if the product doesn’t exist yet in the dictionary.sorted function to sort the product_totals dictionary. Since dictionaries can be converted to a list of their items (key-value pairs), we sort these items.lambda item: item[1], which returns the quantity from each (product, quantity) tuple. Setting reverse=True sorts the list in descending order based on the quantity.sorted_products and print each product along with its aggregated quantity.The output of the code example, which aggregates and sorts the total quantity sold for each product, is as follows:
makefileBanana: 75 Apple: 74 Orange: 27