Dec-27-2021, 11:52 AM
Hello,
I'm going through an introductory book on Python and there's a section in which the author presents some code to demonstrate the concept of nested dictionaries. I understand everything that is going on in the code and I've run the code myself in Python 3.8.7 and confirmed that it works. But it's re-raising a few basic questions in my mind regarding the syntax of how user-defined functions and for loops work in Python that I've had when looking at other Python code.
Here is the code that I'm referring to:
Question 2: I understand what the for loop is doing here in terms of iterating through the key-value pairs in the dictionary. But as far as I can tell, neither "k," "v," "guests," nor "item" (or "items") have been defined yet in the code. So again, how does Python know what they are referring to?
Thanks so much in advance for any help.
I'm going through an introductory book on Python and there's a section in which the author presents some code to demonstrate the concept of nested dictionaries. I understand everything that is going on in the code and I've run the code myself in Python 3.8.7 and confirmed that it works. But it's re-raising a few basic questions in my mind regarding the syntax of how user-defined functions and for loops work in Python that I've had when looking at other Python code.
Here is the code that I'm referring to:
allGuests = {'Alice': {'apples': 5, 'pretzels': 12}, 'Bob': {'ham sandwiches': 3, 'apples': 2}, 'Carol': {'cups': 3, 'apple pies': 1}} def totalBrought(guests, item): numBrought = 0 for k, v in guests.items(): numBrought = numBrought + v.get(item, 0) return numBrought print('Number of things being brought:') print(' - Apples ' + str(totalBrought(allGuests, 'apples'))) print(' - Cups ' + str(totalBrought(allGuests, 'cups'))) print(' - Cakes ' + str(totalBrought(allGuests, 'cakes'))) print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches'))) print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))Question 1: On line five, I understand that the totalBrought function is being defined in relation to "guests" and "item." But guests and item have not been defined yet in the code (at least as far as I can tell). So how does Python know what they are referring to?
Question 2: I understand what the for loop is doing here in terms of iterating through the key-value pairs in the dictionary. But as far as I can tell, neither "k," "v," "guests," nor "item" (or "items") have been defined yet in the code. So again, how does Python know what they are referring to?
Thanks so much in advance for any help.