3/18 output question


#1

So this was marked as correct but why is it that with this code:

my_dict = {
  "Name": "Inigo montoya",
  "You" : "killed my father",
  "Prepare" : "to die"
}

for key in my_dict:
  print "Name", my_dict["Name"],
  
for key in my_dict:
  print "You", my_dict["You"],
  
for key in my_dict:
  print "Prepare", my_dict["Prepare"]

I get each answer three times?


#2

you have 3 loop, each loop will loop over the dictionary and print key + value.

3 * 3 is 9.


#3

Reason for your output

for key in my_dict: - This line will make the execute the loop 3 times as there are 3 items in the dictionary.

Now, the line print "Name", my_dict["Name"] will print “Name” and the value at key Name. And it is inside the loop, so it will be repeated for three times.
Similarly in each loop statement. So, therefore, your answer is printed 3 times each.

Solution
As there are 3 items in your dictionary so the loop is running for three times, so use just 1 loop as follows:

for key in my_dict:
  print key, my_dict[key]

the key variable will be replaced by “Name”, You" and “Prepare” each time the loop iterates, and you don’t need to write the key values by yourself, as it is impractical in case of a dictionary for some hundreds or thousands of items.


#5

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