easy +8 pts

Revenue by Month

Aggregate daily sales into monthly revenue totals with a clean dictionary.

You are given a list of sales records. Each record is a tuple `(date, amount)` where `date` is a string in the format `'YYYY-MM-DD'` and `amount` is a non-negative number (int or float). Your task is to write a function `revenue_by_month(records)` that returns a dictionary mapping each year-month (as a string `'YYYY-MM'`) to the total revenue for that month. The dictionary must be sorted by year-month in ascending order. If the input is empty, return an empty dictionary. Amounts may be floats, and the totals should be returned with the same precision as the sum (i.e., do not round).

Constraints

• 0 ≤ len(records) ≤ 10^5 • date strings are always valid in format `YYYY-MM-DD` with zero-padded month/day. • amounts are non-negative numbers (int or float). • Time complexity should be O(n) for aggregation plus O(m log m) for sorting the distinct months, where n is the number of records and m is the number of distinct months.

Example

>>> revenue_by_month([
...     ('2023-01-15', 100),
...     ('2023-01-20', 250.5),
...     ('2023-02-01', 75.5)
... ])
{'2023-01': 350.5, '2023-02': 75.5}
>>> revenue_by_month([])
{}
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use slicing on the date string to extract the first 7 characters (year and month).
Iterate through records and accumulate totals in a dictionary.
After aggregation, sort the items by key to produce the final ordered dictionary.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.