Python Python Collections (2016, retired 2019) Dictionaries Dictionary Iteration

How was 'course' defined as a key?

Kenneth used...'for course in course_minutes: print(course)'

to get a key printed. How was course defined for the key? Are naming conventions for dictionaries always set up as "key_value = {}"?


2 Answers

Chris Freeman
Chris Freeman
Treehouse Moderator 58,893 Points

The default way to iterate over a dict is by keys. The following two lines are functionally equivalent:

for course in course_minutes:

for course in course_minutes.keys():

The other two ways to iterate over a dict:

for course in course_minutes.values():   # loop over the dict values

for course, value in course_minutes.items():  # loop over the dict key and values as pairs

Hello Evan, when you iterating something with a for loop it goes like this (for x in list:) x actually is something that we name it anyway we like, it represents the item that we are right now iterating through. For example

something = ["Hey", "Hello", "Bonjour"]
for x in something:
     print(x) #The first time through the loop x represents Hey
                  #the second time Hello and the third time Bonjour

As for how he got the key from the loop this is what happend: He looped through the dictionary which gave him only the keys, so he wrote exactly what I wrote in the example but he added x.value() Soooo every time he was going to print x which is the item of the dictionary he adds the .value() which takes the x key and returns it's value :p simple right?

I hope you understood it, if I am wrong somewhere correct me I just finished the lesson.