Lambda functions in expense tracker

Hey folks, I’m trying to wrap my head around how these lambda functions are being used and the expense/argument.

In the following code associated with the exercise I get being able to use expense as its being created in the for loop, but I’m unsure of how we are using expense in the other functions if expense is a local variable for the print_expenses() function. I’m obviously missing something in my understanding. Thanks in advance for any help!

def print_expenses(expenses):
   for expense in expenses:
       print(f'Amount: {expense["amount"]}, Category: {expense["category"]}')
   
def total_expenses(expenses):
   return sum(map(lambda expense: expense['amount'], expenses))
   
def filter_expenses_by_category(expenses, category):
   return filter(lambda expense: expense['category'] == category, expenses)

They are not the same expense. lambda defines a function. In here parameter of that function is expense.

def total_expenses(expenses):
   return sum(map(lambda expense: expense['amount'], expenses))

This can be written without lambda:

def get_expense_amount(expense):
    return expense['amount']


def total_expenses(expenses):
   return sum(map(get_expense_amount, expenses))

Yeah, I get they are not the same expense. I’m still just wrapping my mind around this concept and it’s use in this case has just confused me.

I just don’t get what the lambda function or the regular function do by them selves. I get we are wanting to pull the values from the ‘amount’ key in the dictionary, just not exactly how it’s working.

map function uses the function that’s passed in, let’s call it callback function. When iterating over elements of the expenses, each element is passed to the callback function.

I’m not sure if that’s going to answer your question.

I appreciate you trying to help me wrap my cave man brain around this. I added the function below to the program and get the error below when I try to get that return value after passing the expenses dictionary which contains 1 expense, so 1 amount and 1 category.

I added an extra choice:

    elif choice == '6':
        print((get_expense_amount(expenses))

and get this error

File “/Users/me/Desktop/freeCodeCamp/Expense_Tracker.py”, line 15, in get_expense_amount
return expense[‘amount’]
~~~~~~~^^^^^^^^^^
TypeError: list indices must be integers or slices, not str

This works if paired with the map function and the entire expenses dictionary as with the total_expenses function, but I would think it would return some value if that value is iterating over the entire expenses dictionary.

I’m probably missing something simple here.

That’s the whole list of expenses, while get_expense_amount expects single expense. Try get_expense_amount(expenses[0])

map does something like this:

new_list = []
for expense in expenses:
    new_list.append(get_expense_amount(expense))

Ah, ok that helps! Thank you!

1 Like