I am having difficulty understanding one part of the code below. I was able to get it correct in an online lesson, so I'm not looking for help finishing it, just understanding this: in the last segment of code, I'm confused about how the x and food work. How is the x going through the items in prices?
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_bill(food):
total = 0
for x in food:
total = total + prices[x]
return total
Python dictionaries
(and other python data structures) implement what is called an iterator
pattern , which takes one item at a time, in order, untill it traverses the whole data structure.
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
The code: for x in food:
simply inits the iterator
in the python dict
and calls it repeatedly to get the next item untill the last item.
That is how it works in python (and other languages as well). Python knows internaly that the dict
implements an iterator
and for
loops call this iterator underneath.
prices
is a dictionary, a mapping of keys (banana, apple, ...) to values (4, 2, ...).
for x in food
means "For every item in the provided list called food
, give it a temporary variable assignment x
and do something with x
."
total = total + prices[x]
means "Assign the current value of total
added to the price of item x
(looked up from prices)". For the first item in food
(banana in this case), you're looking for a corresponding price in prices
(which is 4). So, you're really saying total = 0 + 4
, then moving onto the next item in food
. Since total
is now set to 4, your assignment becomes total = 4 + price['orange']
, or 4 + 1.5
. Once the list has been iterated entirely, you have a total
sum (7.5 in your example).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.