Skip to content

script_8.py - Map, Filter, Reduce

Code

See script_8.py for full code.

Explanation

Line 8: from functools import reduce - reduce is in functools module (not built-in) - Functional programming tool

Line 11-18: List of dictionaries - transactions is list type - Each element is dict with keys: id, amount, category, status

Line 23: completed = list(filter(lambda t: t["status"] == "completed", transactions)) - filter() is built-in function - Takes predicate function and iterable - lambda t: t["status"] == "completed" returns boolean - Only elements where lambda returns True are included - Returns filter object (iterator), converted to list - completed is new list

Line 27: amounts = list(map(lambda t: t["amount"], completed)) - map() applies function to each element - lambda t: t["amount"] extracts amount value - Transforms list of dicts to list of integers - Returns map object, converted to list

Line 31: total_revenue = reduce(lambda acc, amt: acc + amt, amounts, 0) - reduce() aggregates list to single value - Takes function, iterable, and optional initial value - Lambda has two parameters: acc (accumulator), amt (current value) - 0 is initial value for accumulator - Processes: 0+100=100, then 100+250=350, then 350+500=850, etc. - Returns single integer (total)

Line 36: cat_revenue = reduce(...) - Combines filter and reduce - First filters transactions by category - Then reduces to sum

Line 45: max_transaction = reduce(lambda a, b: a if a["amount"] > b["amount"] else b, completed) - Ternary operator in lambda - Compares two dicts, keeps one with higher amount - No initial value (uses first element) - Finds maximum by comparison