easy +10 pts

Pivot sales by product

Transform raw sales records into a product-major pivot table with monthly totals.

You are given a list of sales records. Each record is a dictionary with three keys: 'product' (a string), 'month' (a string like '2024-01'), and 'amount' (an integer or float). Write a function `pivot_sales(records)` that returns a dictionary where each key is a product name and each value is another dictionary mapping each month that the product had at least one sales record to the total amount sold in that month. Even if the total is zero (due to cancellation), the month should still appear because at least one record exists for that product and month. The product dictionary should only include months that appear in the records for that product. Do not include months with zero sales records. The order of keys does not matter.

Constraints

- 0 <= len(records) <= 10^5 - product: non-empty string, length <= 100 - month: string in 'YYYY-MM' format - amount: integer or float, |amount| <= 10^6 - Return a dict: product -> {month: total_amount}

Example

>>> pivot_sales([
...     {'product': 'apple', 'month': '2024-01', 'amount': 10},
...     {'product': 'banana', 'month': '2024-01', 'amount': 5},
...     {'product': 'apple', 'month': '2024-02', 'amount': 3},
...     {'product': 'apple', 'month': '2024-01', 'amount': 7},
... ])
{'apple': {'2024-01': 17, '2024-02': 3}, 'banana': {'2024-01': 5}}
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a dict of dicts keyed by product, then by month.
Initialize the inner month key to 0 before adding the amount.
For each record, set the month to an existing total plus the new amount.
Handle empty input by returning an empty dictionary.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.