This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Dictionary type

Another common data structure is a dictionary. You may have encountered them in other programming languages as maps, hash tables or associative arrays.

A dictionary acts as a lookup table. It it made up of (key, value) pairs. You use a unique key to retrieve its corresponding value.

An example use case for a dictionary would be to retrieve a student’s name given the student’s ID.

Python implements a dictionary as a dict type.

dicts are unsorted.

The keys must be unique and immutable (e.g. numbers, strings, tuples). You cannot for example use a list as a key.

Here is an example of how you would define a dictionary:

>>> student_dict = {"00-01-30": "Ali", "00-02-11": "Simon", 
...                 "00-05-67": "Francesca", "00-09-88": "Cho"
...                }
>>> print(student_dict)

Alternatively:

>>> student_dict = {}                   # or student_dict = dict()
>>> student_dict["00-01-30"] = "Ali"
>>> student_dict["00-02-11"] = "Simon"
>>> student_dict["00-05-67"] = "Francesca"
>>> student_dict["00-09-88"] = "Cho"
>>> print(student_dict)

Question: What happens if you subsequently add student_dict["00-01-30"] = "Josiah"? Will Python allow this? What will happen to "Ali"? Test it out to confirm!

Retrieving an item from a dictionary

As you would expect, you can retrieve the value of a dictionary given a key.

>>> best_student = student_dict["00-02-11"]
>>> print(best_student)

But what if the key cannot be found? What happens?

>>> student_dict["00-11-22"]    # What error message do you get? 

So you should check whether the key exists before trying to use the key to retrieve a value.

>>> if "00-11-22" in student_dict:
...    active_student = student_dict["00-11-22"]

Alternatively, you can use dict’s get() to retrieve a value. The method will conveniently assign a default value if the key does not exist.

>>> real_student = student_dict.get("00-09-88", "John Doe")
>>> print(real_student)
>>> imaginary_student = student_dict.get("11-22-33", "John Doe")
>>> print(imaginary_student)

Other useful methods

If you need the complete list of keys:

>>> ids = student_dict.keys()
>>> print(ids)
>>> print(type(ids))
>>> ids[0]              # Can you do this?

If you need to access the elements in the dict_keys instance, you can cast it into a list

>>> id_list = list(ids)
>>> id_list[0]

Similarly, dict’s values() method give you the list of values.

There is also the items() method which give you a list of (key, value) pairs.

Test them out!

>>> print(student_dict.values())
>>> print(student_dict.items())