pythonintermediate10 minutes
Build a Function to Group and Summarize Sales Data by Category
Create a Python function that takes a list of sales records and returns a summary dictionary grouping total sales by product category.
Challenge prompt
Write a function named 'summarize_sales_by_category' that accepts a list of dictionaries. Each dictionary represents a sale with keys 'product', 'category', and 'amount'. The function should return a dictionary where each key is a category and the value is the sum of amounts for that category.
Guidance
- • Iterate over each sale record in the input list.
- • Use a dictionary to accumulate the sum of amounts keyed by category.
- • Ensure the function works efficiently for any number of sales records.
Hints
- • Use the dict.get method to provide a default value when adding amounts.
- • Remember to initialize the category sum to zero the first time you encounter it.
Starter code
def summarize_sales_by_category(sales):
# Your code here
passExpected output
{'Electronics': 450, 'Clothing': 300, 'Books': 150}
Core concepts
dictionaryloopsaggregation
Challenge a Friend
Send this duel to someone else and see if they can solve it.