In Listing 9.8, a particular key is updated to a new value. However, if the key does not already exist,
a new key/value pair is created. Therefore, you can use this method not only to update a dictionary
but add new elements as well.
When you need to delete a key/value pair from a dictionary, you use the following syntax:
del dictionary_name[key]
However, if the key/value pair does not exist in the dictionary, the del operation throws an error
exception. Listing 9.9 uses an if statement to make sure the key does exist, before deleting the
element.
LISTING 9.9 Deleting a Dictionary Element
Click here to view code image
>>> if '400A42' in student:
... del student['400A42']
...
>>> student
{'300A04': 'Jason Jones', '000B35': 'Raz Berry Pi'}
>>>
By the Way: has_key No Longer Available
The dictionary operation has_key allowed you to determine whether a particular key
existed in a dictionary. For Python v3, this dictionary operation is no longer available.
Instead, you now use the if statement as shown in Listing 9.9.
Managing a Dictionary
In addition to the ones you’ve already seen this hour, a few other dictionary operations may prove
useful when you’re using a Python dictionary. Table 9.1 lists them, as well as a few of the ones
you’ve already seen this hour.
TABLE 9.1 Python Dictionary Management Operations
Now that you have an idea of the various dictionary operations, you can learn about how to program
using dictionaries.