This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 4: 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?
???
>>> 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])
???

The main use of these methods is as an iterator in a for loop. For example:

1
2
3
4
5
6
student_dict = {"00-01-30": "Ali", "00-02-11": "Simon", 
                 "00-05-67": "Francesca", "00-09-88": "Cho"
                }

for (id, name) in student_dict.items():
    print(f"ID: {id}; NAME: {name}")

Line 5 can also be written as for id, name in student_dict.items(): if you prefer.

The output will be:

ID: 00-01-30; NAME: Ali
ID: 00-02-11; NAME: Simon
ID: 00-05-67; NAME: Francesca
ID: 00-09-88; NAME: Cho