Chapter 5: Sets and dictionaries

Dictionary methods

face Josiah Wang

Recall that everything is an object in Python, including dict.

This means that dict also has some built-in methods available for your convenience.

You will most likely use these three dict methods quite often: .keys(), .values(), .items(). Try exploring these three methods, and examine the outputs marked ??? below - are they what you expected?

>>> student_dict = {"00-01-30": "Ali", "00-02-11": "Simon", 
...                 "00-05-67": "Francesca", "00-09-88": "Cho"
...                }
>>> ids = student_dict.keys()
>>> print(ids)
???
>>> print(type(ids))
???
>>> ids[0] # Can you do this? Why not? What does the error say?
???
>>> print(list(student_dict))
???
>>> names = student_dict.values()
>>> print(names)
???
>>> print(type(names))
???
>>> pairs = student_dict.items()
>>> print(pairs)
???
>>> print(type(pairs))
???
>>> entries = list(pairs)
>>> print(entries)
???
>>> print(entries[0])
???