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 Introducing Dictionaries Accessing Keys and Values

dict.keys() and dict.values() return view objects, not lists

In the video, it is stated that

dict.keys()

and

dict.values()

return lists, however they actually return view objects that change when the dictionary changes.

sorted(dict.keys())

returns an actual list that does not change when the dictionary changes. This becomes important if whatever is returned is stored with a variable. To illustrate:

>>>course = {'teacher':'Ashley', 'title':'Introducing Dictionaries','level':'Beginner'}
>>>view = course.keys())
>>>view
dict_keys(['teacher', 'title', 'level'])
>>>my_list = sorted(course.keys())
>>>my_list
['level', 'teacher', 'title']
>>>course['student'] = 'Paul'
>>>view
dict_keys(['teacher', 'title', 'level', 'student'])
>>>my_list
['level', 'teacher', 'title']

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,457 Points

Correct! A dictionary view object were implemented in Python 3.x [see PEP3106 - Revamping dict.keys(), .values() and .items()] as an improvement over the Python 2.x keys(), values(), and items(). The dictionary view object has set-like behavior.

Finding which keys are common to two dictionaries:

>>> d = dict(a=1, b=2, c=3, d=4)
>>> d.keys()
dict_keys(['a', 'b', 'c', 'd'])
>>> d['e'] = 5
>>> d
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d.keys()
dict_keys(['a', 'b', 'c', 'd', 'e'])
>>> e = dict(d=1, e=2, f=3, g=4)
>>> e
{'d': 1, 'e': 2, 'f': 3, 'g': 4}
# Find the common keys
>>> d.keys() & e.keys()
{'d', 'e'}

Great Post. Thanks for helping improve the Community!!