Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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 68,423 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.