Data Manipulation with Tuples

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.

Python Code Example

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}")

Detailed Code Explanation

  1. Data Structure Initialization:
    • We initialize a list of tuples called 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.
  2. Aggregation Logic:
    • We loop over each tuple in the 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.
    • For each tuple, we add the quantity to the corresponding product’s total in product_totals. The defaultdict takes care of initializing the quantity to zero if the product doesn’t exist yet in the dictionary.
  3. Sorting Logic:
    • We use the 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.
    • The key for sorting is defined by a lambda function 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.
  4. Output:
    • Finally, we iterate over the sorted list sorted_products and print each product along with its aggregated quantity.

Output

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