Python Python Collections Dictionaries Dictionary Iteration

Hussein Amr
Hussein Amr
2,461 Points

Didn't get how printing the minutes of the courses works

for course in course_minutes:
      print(course_minutes[course])

How does that print the values exactly?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 55,471 Points

Let's look at the two statements. First:

for course in course_minutes:

Says:

  • treat course_minutes as an iterable object
  • take each item from the iterable and assign it to the variable course
  • then run the loop code using this new value of course

When a dict is used in the context of an iterable, it will respond with a list of the dictionary keys. So course will contain the various course names.

      print(course_minutes[course])

Says:

  • use the course defined by the for loop as the key to the dict course_minutes
  • look up the value, and print it

Hope this helps. Post back if you need more help. Good Luck!!

Idan shami
Idan shami
13,251 Points

I don't understand why if the course defined as a key it means to look up the value, why it is saying that, i just cannot understand it.

Chris Freeman
Chris Freeman
Treehouse Moderator 55,471 Points

It is the square brackets around course that designates it semantically as a dict key In dict notation, an item is looked up using the form some_dict[key]. Otherwise course is just a string object.