# Question about lesson 6 in A Day at the Supermarket

#1

Hello,

I had a question about the following exercise. I completed it already, but I don’t understand why you can archieve the right outcome with just 3 times print. looping trough a dictionary and printing it doesn’t come out in a particular order if I understood correctly in a earlier lesson. So how is it possible that the right price and stock will be printed out under the right kind of fruit and not random. I hope you understand my question since I don’t really know how to explain haha.

``````prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

for fruit in prices:
print fruit
print "price: %s" % prices[fruit]
print "stock: %s" % stock[fruit]
``````

Greetings!

Marije

#2

dictionaries consist of key value pairs. Each value is associated with a key. So even though the order of dictionary keys might be “random”, the values associated will the keys stick with the keys

if you have a bunch of people (key) with each a dog on a leash (value), and you would re-arrange there order, each dog owner will keep its own dog (given they have it on a leash). Same with dictionaries, the way dictionaries are implemented in python might mean the keys get shuffled, but each key will keep its associated value

#3

I understand that, but I didn’t define in each print WHICH key I was requesting. If I would have done that, my code would look something like this:

``````for fruit in prices:
print "banana"
print "price: " % prices["banana"]
print "stock: " % stock["banana"]

etc (for all the kind of fruits)
``````

However I know that is not necessary. But why in my original code isn’t this for example the outcome?:

banana
price: 2
stock: 32

So how does my second and third print know that I requested banana in my first print. So hard to explane what I mean, but I just really want to understand the why and how in my code so I can use it in other scripts in the future.

Thanks!

#4

all of them, using the `for .. in` loop will request each key and assign it to the iterator (`fruit`), execute code in the for block, then move on to the next key, until its done with all keys

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.