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.