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 trialBenyamin Kohanchi
Courses Plus Student 2,342 PointsWhy does the beginning of Ashley's "for" loop end with "course.items():" as opposed to just "course:" ?
Here is the code:
course = {'teacher':'Ashley', 'title':'Introducing Dictionaries', 'level':'Beginner'}
for key, value in course.items():
print(key, value)
What is the reason the code needs to be course.items(): instead of course:? Thanks in advance 😁
1 Answer
Jeff Muday
Treehouse Moderator 28,722 PointsGood question-- at first dictionaries don't seem like something you would use much, but they are an amazing way to structure data!
To answer your question:
You want to use course.items()
is because course
is a dictionary. If you iterate through a dictionary, 99 % of the time you will want both the KEY and the VALUE from the course dictionary iterable.
But there are ways to just loop through the keys or just the values... see below.
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> course = {'teacher':'Ashley', 'title':'Introducing Dictionaries', 'level':'Beginner'}
>>>
>>> for key, value in course.items():
... print(key, value)
...
teacher Ashley
title Introducing Dictionaries
level Beginner
If we only loop through course, we will get a syntax error:
>>> for key, value in course:
... print(key, value)
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
We can loop through just the keys like this:
>>> for key in course:
... print(key)
...
teacher
title
level
We can also loop through the keys this way:
>>> for key in course.keys():
... print(key)
...
teacher
title
level
We can also loop through ONLY the values like this:
>>> for value in course.values():
... print(value)
...
Ashley
Introducing Dictionaries
Beginner
Benyamin Kohanchi
Courses Plus Student 2,342 PointsBenyamin Kohanchi
Courses Plus Student 2,342 PointsGreat, thanks for the in depth explanation Jeff! Much appreciated 😁