9. Something of value - Question about how "for" works


I don't know if I get it right, so I'm going to ask:

I wrote that:

for key in prices:
print prices[key] * stock[key]
total = total + prices[key]*stock[key]

and it worked, nice, but in my view, I only said to the loop go through the "prices" dictionary. I know I'm wrong because well, the code worked, and the loop clearly went through all keys in stock, so:

How python went through all the keys in "stock"? By position? Like, first key in "prices" go with the first key in "stock", the second with the second and so on? What if the numbers of keys were bigger in "prices" than in the "stock"? The code would run until he won't find a key in one of them? Like 6 keys in "prices" and 5 in "stock", the code would do only five operations, because there's no sixth key in "stock" to match with the sixth key in "prices"?

Another question, and I don't know if this is covered by a future lesson, but I'm gonna ask anyway. There's a way to choose what keys I want to manipulate? For example, I want the loop to work only with the keys 5, 6, 7 and 8, there's a way to do that?


you iterated over keys in prices and stored that in key, prices and stock has the same key but different value


Yes, if they dictionaries had unbalanced numbers of items, this would throw an error.

You could access [5, 6, 7, 8] using a range().

for i in range(5, 9)