How to Extract Data by Category in Python with Dictionaries and Sets

Use set comprehensions and a defaultdict to extract product names by category and compute total prices per category from a list of dictionaries.

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

Python code

38 lines
Python 3.9+
from collections import defaultdict

# Sample data: products with categories and prices
product_data = [
    {"name": "Apple", "category": "fruit", "price": 0.50},
    {"name": "Banana", "category": "fruit", "price": 0.30},
    {"name": "Carrot", "category": "vegetable", "price": 0.80},
    {"name": "Bread", "category": "grain", "price": 2.00},
    {"name": "Broccoli", "category": "vegetable", "price": 1.50},
]

def extract_by_category(products, category):
    """Return a set of product names in the given category."""
    return {product["name"] for product in products if product["category"] == category}

def total_price_by_category(products):
    """Return a dict mapping each category to its total price."""
    totals = defaultdict(float)
    for product in products:
        totals[product["category"]] += product["price"]
    return dict(totals)

if __name__ == "__main__":
    fruits = extract_by_category(product_data, "fruit")
    print(f"Fruits: {fruits}")

    vegetables = extract_by_category(product_data, "vegetable")
    print(f"Vegetables: {vegetables}")

    totals = total_price_by_category(product_data)
    print(f"Total prices by category: {totals}")

    # Demonstrate set operations with extracted data
    all_vegetables = {p["name"] for p in product_data if p["category"] == "vegetable"}
    cheap_vegetables = {p["name"] for p in product_data if p["category"] == "vegetable" and p["price"] < 1.00}
    print(f"All vegetables: {all_vegetables}")
    print(f"Cheap vegetables (< $1.00): {cheap_vegetables}")
    print(f"Cheap vegetables as subset: {cheap_vegetables.issubset(all_vegetables)}")

Output

stdout
Fruits: {'Apple', 'Banana'}
Vegetables: {'Carrot', 'Broccoli'}
Total prices by category: {'fruit': 0.8, 'vegetable': 2.3, 'grain': 2.0}
All vegetables: {'Carrot', 'Broccoli'}
Cheap vegetables (< $1.00): {'Carrot'}
Cheap vegetables as subset: True

How it works

The extract_by_category function uses a set comprehension that iterates over the list of products, filtering by category, and builds a set of unique names. The total_price_by_category function leverages defaultdict(float) so that missing keys are auto-initialized to 0.0, allowing direct addition of prices. When accessing a missing key, defaultdict creates it on the fly, simplifying accumulation. The issubset call demonstrates set operations that are handy for comparing extracted groups.

Common mistakes

  • Forgetting to convert defaultdict back to a regular dict, which can cause keys to appear unexpectedly when accessed.
  • Using a list instead of a set when you need unique names, which can lead to duplicates.
  • Not accounting for negative prices when using `issubset` logic, though here it's fine.

Variations

  1. Replace the set comprehension with a generator expression and `set()` for clarity.
  2. Use `collections.Counter` to count occurrences instead of summing prices.

Real-world use cases

  • Grouping e-commerce order items by category to compute revenue per product line.
  • Filtering a dataset by a label (e.g., 'vegetable') to build a unique set of matching records for reporting.
  • Aggregating log entries by severity level to track error counts and totals.

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.