By the Way: Not a List
For Listing 9.6, you might think that you could just enter the list operation
key_list.sort (), but that will not work. The variable key_list is a
dictionary key (dict_keys) object type and not a list. Thus, you cannot use a list
operation on it!
In Listing 9.7, the key_list variable is sorted first. Then it is used as an iteration in the for loop,
to traverse the dictionary.
LISTING 9.7 Using a Sorted Key List to Traverse a Directory
Click here to view code image
>>> key_list = student.keys()
>>> type (key_list)
<class 'dict_keys'>
>>>
>>> key_list = sorted(key_list)
>>> type (key_list)
<class 'list'>
>>>
>>> for the_key in key_list:
... print(the_key, end = ' ')
... student[the_key]
...
000B35 'Raz Pi'
300A04 'Jason Jones'
400A42 'Paul Bohall'
>>>
Notice in Listing 9.7 that the variable key_list changes object types after it is sorted! It starts out
as dict_keys and becomes a list object type.
Updating a Dictionary
Remember that keys are immutable, so they cannot be changed. However, you can update a key’s
associated value. The syntax for doing so is database_name[key]=value. In Listing 9.8, the
student’s name associated with the student ID number (key) '000B35' is changed.
LISTING 9.8 Updating a Dictionary Element
Click here to view code image
>>> student['000B35'] #Element shown before the change.
'Raz Pi'
>>> student['000B35'] = 'Raz Berry Pi'
>>>
>>> student['000B35'] #Element shown after the change.
'Raz Berry Pi'
>>>