14/19 Looping over a dictionary


#1



Can someone help me with this code?


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

    for key in d:
        # Your code here!
        print d.keys(), d.values()


Codecademy prints, "Oops, try again. It looks like your code did not print "b berry"."

Console prints:
    ['a', 'c', 'b'] ['apple', 'cherry', 'berry']    # I printed berry, didn't I?
    ['a', 'c', 'b'] ['apple', 'cherry', 'berry']
    ['a', 'c', 'b'] ['apple', 'cherry', 'berry']
    None

To me there is nothing wrong.


#2



Tried this too, but it did not work.


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

    for key in d:
        # Your code here!
        print "%s  %s" %(key, d[key])  


Codecademy prints, " Oops, try again. It looks like your code did not print "b berry"."

Console prints:
    a  apple
    c  cherry
    b  berry
    None


#3

you are iterating over d dictionary and you are not using key in your print
key holds what's iterated over d

you should print key, d[key]


#4

But I printed "print key, d[key]" din't I?


#5

in second try you did, but guess codecademy want's you to do it without %s


#6

You have a double-space in here ""%s %s"".


#8

I think the most effective solution is to use:

print key, d[key]


#9

You misunderstood what was asked.
You should "a apple" as a unique string and iterate...


#10

print key + ' '+ d[key]

#11

This worked for me...

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

for key in d:
    print "%s %s" %(key, d[key])

#12

try this one,..since space is considered, why not try thi?
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:

print key," ",d[key]

#13

reply correct:

for key in d:
# Your code here!
print key, d[key]


#14

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

for key in d:
# Your code here!
print key,"b",d[key]

So this code worked for me, but I don't understand why?


#15

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

for key in d:
# Your code here!
print "%s %s" %(key,d[key])


#16

a b apple
c b cherry
b b berry
None

Yes, it worked but you added "b" in between the key and its values.

The correct code is print key, d[key]

meaning print each key followed by printing each of its value.

check out the hint.


#17

this is THE correct answer...

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

for key in d:
# Your code here!
print d[key], key


#18

Thank you, I shall try that later.


#19

This is weird this topic should have closed... why didn't it?


#20

Sorry I bothered you


#21

You didn't... :grin: