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

Chapter 4: Dictionaries

Dictionaries

face Josiah Wang

So far, we have looked at sequence types like lists and tuples.

Sequence is not the only complex data structure available in Python.

Python also provides another data type called dict (short for dictionary). You may have encountered these 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.

Dictionaries are made up of (key, value) pairs

Here is an example of how you would define a dict type in Python:

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

Alternatively, if you already have your data in a list of tuple pairs, you can just pass them on directly to dict().

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

You can also start with an empty dictionary and add in items later.

>>> 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)
{'00-01-30': 'Ali', '00-02-11': 'Simon', '00-05-67': 'Francesca', '00-09-88': 'Cho'}

As you can see above, you index an item in a dictionary using keys (and not integer sequences as in a list or tuple).

Dictionary keys must be unique and immutable (e.g. numbers, strings, tuples). You CANNOT for example use a list as a key (try it and see what happens!) This is quite logical - how do you expect a key to be consistent if you can modify it any time?

For the official Python interpreter version 3.6 and above, the dictionary maintains the order of the keys as you inserted them. This might not happen if you are using a different kind of Python interpreter, so it is better to treat dictionary entries as unordered!