Advanced Code Example — Containers#

This example demonstrates all four container types working together in a realistic customer analytics workflow. You’ll see how lists, dictionaries, tuples, and sets each play a distinct role in organizing and analyzing business data.


Business Scenario#

You manage customer data for a retail analytics team. Given a set of customer transaction records, you need to:

  1. Store customer profiles as dictionaries
  2. Track purchase history as lists
  3. Store store metadata as tuples (fixed reference data)
  4. Identify unique product categories using sets
  5. Compute summary analytics across all containers

Code#

# ── Store Reference Data (Tuples — fixed, won't change) ─────────────
store_northwest = ('Store-NW-001', 'Seattle', 47.6062, -122.3321)
store_southwest = ('Store-SW-001', 'Phoenix', 33.4484, -112.0740)

# ── Customer Records (List of Dictionaries) ──────────────────────────
customers = [
    {
        'name': 'Alice Johnson',
        'customer_id': 1001,
        'region': 'Northwest',
        'is_premium': True,
        'purchases': [250.50, 180.75, 420.25, 310.00],
        'categories': ['Electronics', 'Apparel', 'Electronics', 'Home Goods']
    },
    {
        'name': 'Bob Martinez',
        'customer_id': 1002,
        'region': 'Southwest',
        'is_premium': False,
        'purchases': [95.80, 215.25, 110.00],
        'categories': ['Apparel', 'Home Goods', 'Apparel']
    },
    {
        'name': 'Carol Chen',
        'customer_id': 1003,
        'region': 'Northwest',
        'is_premium': True,
        'purchases': [300.00, 290.75, 300.00],
        'categories': ['Electronics', 'Beauty', 'Electronics']
    }
]

# ── Analysis Using All Four Container Types ──────────────────────────
print("=" * 50)
print("  CUSTOMER PORTFOLIO REPORT")
print("=" * 50)

all_categories = set()   # Set: collect unique categories across all customers
regional_totals = {}     # Dictionary: accumulate revenue per region

for customer in customers:
    # Access dictionary fields
    name = customer['name']
    region = customer['region']

    # Work with list: sum purchases
    purchase_list = customer['purchases']
    total = sum(purchase_list)
    avg = total / len(purchase_list)

    # Work with set: unique categories this customer purchased
    unique_cats = set(customer['categories'])
    all_categories.update(unique_cats)

    # Accumulate regional totals in a dictionary
    if region not in regional_totals:
        regional_totals[region] = 0.0
    regional_totals[region] += total

    # Print customer summary
    print(f"\n  {name} (ID: {customer['customer_id']})")
    print(f"    Region   : {region}")
    print(f"    Premium  : {'Yes' if customer['is_premium'] else 'No'}")
    print(f"    Total    : ${total:,.2f}")
    print(f"    Avg/Buy  : ${avg:,.2f}")
    print(f"    Unique Categories: {sorted(unique_cats)}")

# ── Regional Summary (Dictionary iteration) ──────────────────────────
print("\n" + "=" * 50)
print("  REGIONAL REVENUE SUMMARY")
print("=" * 50)
for region, revenue in sorted(regional_totals.items()):
    print(f"  {region:<15} ${revenue:,.2f}")

# ── Store Reference (Tuple access by index) ──────────────────────────
print("\n" + "=" * 50)
print("  STORE LOCATIONS")
print("=" * 50)
for store in [store_northwest, store_southwest]:
    store_id, city, lat, lon = store   # tuple unpacking
    print(f"  {store_id}{city} ({lat}, {lon})")

# ── All Unique Categories (Set result) ───────────────────────────────
print("\n" + "=" * 50)
print(f"  ALL UNIQUE PRODUCT CATEGORIES ({len(all_categories)} total):")
for cat in sorted(all_categories):
    print(f"    • {cat}")
print("=" * 50)

Expected Output#

==================================================
  CUSTOMER PORTFOLIO REPORT
==================================================

  Alice Johnson (ID: 1001)
    Region   : Northwest
    Premium  : Yes
    Total    : $1,161.50
    Avg/Buy  : $290.38
    Unique Categories: ['Apparel', 'Electronics', 'Home Goods']

  Bob Martinez (ID: 1002)
    Region   : Southwest
    Premium  : No
    Total    : $421.05
    Avg/Buy  : $140.35
    Unique Categories: ['Apparel', 'Home Goods']

  Carol Chen (ID: 1003)
    Region   : Northwest
    Premium  : Yes
    Total    : $890.75
    Avg/Buy  : $296.92
    Unique Categories: ['Beauty', 'Electronics']

==================================================
  REGIONAL REVENUE SUMMARY
==================================================
  Northwest       $2,052.25
  Southwest         $421.05

==================================================
  STORE LOCATIONS
==================================================
  Store-NW-001 — Seattle (47.6062, -122.3321)
  Store-SW-001 — Phoenix (33.4484, -112.074)

==================================================
  ALL UNIQUE PRODUCT CATEGORIES (4 total):
    • Apparel
    • Beauty
    • Electronics
    • Home Goods
==================================================

Key Concepts Demonstrated#

ContainerRole in This Example
Listpurchases list per customer; iterated with sum() and len()
DictionaryCustomer records; regional_totals accumulator
TupleStore location data; unpacked with multiple assignment
SetUnique category collection; update() to merge, sorted() to display

Next: Jupyter Notebook →