pythonintermediate10 minutes
Refactor and Simplify Nested Loops for Data Aggregation
Improve the structure and readability of a Python function that aggregates sales data from multiple stores and products, while preserving its original behavior.
Challenge prompt
You are given a function that processes sales data from several stores to calculate the total sales per product category. The current implementation uses multiple nested loops, redundant conditions, and some repeated code blocks, making it hard to maintain and understand. Refactor the function to simplify the logic, reduce nesting, and improve readability without changing the output.
Guidance
- • Focus on removing unnecessary loops or conditions and consolidate repeated code.
- • Use intermediate variables or helper functions if it makes the code clearer.
- • Ensure that the function behavior and final output remain exactly the same after refactoring.
Hints
- • Look for places where you can use dictionary methods like get() to avoid explicit conditionals.
- • Consider looping over data just once where possible, using data structures to hold intermediate results.
- • Use descriptive variable names and consider list/dictionary comprehensions where applicable.
Starter code
def calculate_total_sales(data):
result = {}
for store in data:
for product in store['products']:
category = product['category']
if category in result:
if product['name'] in result[category]:
result[category][product['name']] += product['sales']
else:
result[category][product['name']] = product['sales']
else:
result[category] = {}
if product['name'] in result[category]:
result[category][product['name']] += product['sales']
else:
result[category][product['name']] = product['sales']
return resultExpected output
{'Electronics': {'TV': 350, 'Radio': 80}, 'Books': {'Novel': 120, 'Comics': 75}}
Core concepts
refactoringnested loopsdictionariescode readability
Challenge a Friend
Send this duel to someone else and see if they can solve it.