Dictionaries
Another powerful data structure is a dictionary. Python implements a dictionary as a built-in dict
type. Dictionaries are equivalent to Hashtable
s or HashMap
s in Java.
In case you are not familiar or have forgotten, a dictionary acts as a lookup table.
It is 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.
Here is an example of how you would define a dict
:
>>> 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()
method 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))
>>> print(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
. In fact, you can just cast the dictionary directly into a list
to achieve the same thing.
>>> id_list = list(ids)
>>> print(id_list[0])
>>>
>>> id_list = list(student_dict)
>>> print(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())