Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
Only a key can be used to access the value. You cannot use a numeric index to access a
key/value element because the elements in a dictionary are associative not positional.

To avoid receiving an error exception for nonexistent dictionary keys, you use the get operation.
This is the basic syntax:


Click here to view code image


database_name.get(key, default)

When the get operation finds a key, it returns the associated value. When the get operation does not
find a key, it returns the string listed in its optional default. Listing 9.5 shows an example of
successfully locating a key in the dictionary and then an unsuccessful attempt.


LISTING 9.5 Using the Dictionary get Operation


Click here to view code image


>>> student.get('000B35','Not Found')
'Raz Pi'
>>> student.get('000B34','Not Found')
'Not Found'
>>>

Notice that when the unsuccessful attempt occurs, the second string (the default) is displayed. That is
because the default allows you to create your own error message. If the default section is not included
in the get operation and the key is not in the dictionary, you receive back the string "None".


You can also use a loop to obtain dictionary values. First, you get a list of the dictionary’s keys by
using the keys operation. The syntax is dictionary_name.keys (). Set the results of this
operation as a value to a variable. You can then use a for loop to traverse the dictionary, as shown
in Listing 9.6.


LISTING 9.6 Using a for Loop to Traverse a Dictionary


Click here to view code image


>>> key_list = student.keys()
>>> print (key_list)
dict_keys(['300A04', '000B35', '400A42'])
>>>
>>> for the_key in key_list:
... print(the_key, end = ' ')
... student[the_key]
...
300A04 'Jason Jones'
000B35 'Raz Pi'
400A42 'Paul Bohall'
>>>

Notice in Listing 9.6 that the students’ ID numbers are not listed in order. Remember in a dictionary,
the elements are unordered. You can solve this display problem by using the sorted function.

Free download pdf