Lesson 7
Objects and Dictionaries
Chapter 4: Dictionaries
Retrieving from dictionaries
As you would expect, you can retrieve the value of a dict
given a key.
>>> student_dict = {"00-01-30": "Ali", "00-02-11": "Simon",
... "00-05-67": "Francesca", "00-09-88": "Cho"
... }
>>> best_student = student_dict["00-02-11"]
>>> print(best_student)
Simon
But what if the key cannot be found? What happens? (Try this!)
>>> 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. You can conveniently assign a default value if the key does not exist.
>>> real_student = student_dict.get("00-09-88", "John Doe")
>>> print(real_student)
Cho
>>> imaginary_student = student_dict.get("11-22-33", "John Doe")
>>> print(imaginary_student)
John Doe