Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 = {}"?

Thanks!

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,082 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.