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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

31 lines
Python 3.9+
def 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

stdout
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

  1. Use `defaultdict(int)` from `collections` to simplify summing quantities in `product_summary`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.