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 Introducing Dictionaries Iterating and Packing with Dictionaries Iterate over Dictionaries

Question Regarding what exactly is being returned from course.items()

Hello,

from W3 Documentation (and also the lecture from Ashley) states that the items method from a dictionary: "Returns a list containing a tuple for each key value pair"

course = {"teacher":'Ashley', "title":'Introducing Dictionaries', "level":'Beginner'}
result = course.items()
print(result)
print(type(result)) #This  returns 'dict_items', shouldn't it the return type be list
#print(result[0]) produces TypeError: 'dict_items' object is not subscriptable

Since it is a list, why is the type not a list, but instead 'dict_items' Also if it is a list shouldn't the individual key:value pairs(stored as a single tuple) be accessible by index values in the list, such as course[0] would return ("teacher":"Ashley")

However, when I try to do that i receive print(result[0]) produces TypeError: 'dict_items' object is not subscriptable.

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

Hey heebers, great question!

The result is a Dict view object. They are dynamic views into a dictionary. If the courses were to change, then view object result would dynamically see the change!!

To get a regular list of (key, value) tuples, convert to a list using list(result).

Post back if you have more questions. Good luck!!

Leah Kelly
Leah Kelly
4,141 Points

The key and the value of the key.