# Looping over a dictionary

#1

Ok, I have cheated a little to get the answer to this lesson. Can someone please explain to me how this works and how you would ever come to the solution?

#2

Hi,
Let me explain what you have to do.
I hope you remember how to work with lists (and didn’t cheat on that one as well ).
If you use a list called alpha for example, you can loop through each value in it by using the for-loop, right?

``````alpha = [1,2,3]
for x in alpha:
print x
``````

Will give you 1, 2 and 3, right?

So you can actually do the same in a dictionary, but it will only print the so-called keys, which are the words or number before the “:” .

For example:

`drinks = ["water": 1.50]`

so the key would be "water.

This makes the first part.

If you type in the value of a list in , it will give you the “position” of the value in the list, like:

``````list_1 = ["banana", "cherry", "apple"]
print list_1["cherry"] #Would print out 1
``````

But if you do the same thing in a dictionary, it will give you the other part of the word (or whatever it’s called ^^)

So if you call the dictionary from before:

`drinks = ["water": 1.50]`
print drinks[“water”] #This will print 1.50

I hope you understand now, how it works

Looping over a dictionary issue
#3

d = {‘a’: ‘apple’, ‘b’: ‘berry’, ‘c’: ‘cherry’}

``````# Your code here!
``````

for key in d:
print (key),(d[key])

hope, you’ll find it useful

#4

Thank you for your response. You really put the explanation across well, and yes I now understand how this works.

Cheers

#5

I have printed exactly that, get the b berry, but it says I did not print b berry.

My code is the exact same, done with and without the parenthesis.