How to Aggregate Order Data with Sets and Dictionaries in Python
Combine sets and dictionaries to find unique products and total quantities from a list of orders in Python.
Python code
31 linesdef find_unique_products(orders):
"""Return set of all products ordered across multiple orders."""
all_products = set()
for order in orders:
all_products.update(order.get("items", []))
return all_products
def product_summary(orders):
"""Build a dictionary mapping each product to its total quantity ordered."""
summary = {}
for order in orders:
for item in order.get("items", []):
product = item["name"]
qty = item["quantity"]
summary[product] = summary.get(product, 0) + qty
return summary
if __name__ == "__main__":
sample_orders = [
{"order_id": 1, "items": [{"name": "apple", "quantity": 3}, {"name": "banana", "quantity": 2}]},
{"order_id": 2, "items": [{"name": "apple", "quantity": 1}, {"name": "orange", "quantity": 5}]},
{"order_id": 3, "items": [{"name": "banana", "quantity": 4}]},
]
products = find_unique_products(sample_orders)
summary = product_summary(sample_orders)
print("Unique products:", sorted(products))
print("Quantity summary:", summary)
Output
Unique products: ['apple', 'banana', 'orange']
Quantity summary: {'apple': 4, 'banana': 6, 'orange': 5}
How it works
The find_unique_products function uses a set to automatically discard duplicate product names across all orders, leveraging set.update() to add multiple items at once. product_summary uses a dictionary to track cumulative quantities per product; the get(product, 0) call initializes missing keys to zero so summing is safe. Both functions gracefully skip orders without an items key using order.get("items", []), preventing KeyErrors. The code is deterministic because the set is sorted before printing, and the dictionary preserves insertion order as per modern Python version
Common mistakes
- Forgetting to use `order.get()` and hitting KeyError when an order lacks 'items'
- Assuming product names are unique without using a set to deduplicate
- Modifying the dictionary while iterating over it
- Not resetting the summary dictionary between test calls
Variations
- Use `defaultdict(int)` from `collections` to simplify summing quantities in `product_summary`
- Use a `Counter` from `collections` to count product occurrences instead of quantities
Real-world use cases
- Generating a list of all SKUs sold across multiple e-commerce orders for inventory reporting.
- Aggregating total quantities per product from daily sales feeds to update stock levels.
- Deduplicating user-selected items from multiple cart events in a recommendation engine.
Sponsored
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.