Python List Comprehension for Sales Data

2026-05-05 11:56:15+08

Efficiency is key in Python development. List comprehensions offer a concise way to create lists, but they can become unreadable if not handled correctly. This prompt helps you generate clean, idiomatic code for data processing.

The Core Prompt

I have a Python list of dictionaries containing sales data: sales = [{'item': 'A', 'price': 10, 'qty': 2}, {'item': 'B', 'price': 20, 'qty': 1}]. Write a list comprehension that calculates the total revenue for each item and returns a new list of dictionaries with 'item' and 'total_revenue'.

Technical Value

Asking for a specific data structure (list of dictionaries) ensures the AI provides code that is ready to be integrated into a larger application or API response.

Usage Tips

  • Add Filtering: Ask the AI to "only include items with a total_revenue greater than 50."
  • Explain: Add "Explain the code step-by-step" to the prompt for educational purposes.

Example AI Output

res = [{'item': s['item'], 'total_revenue': s['price'] * s['qty']} for s in sales]