• No results found

accesses a particular dictionary value, using the [] operator Dictionary values are accessed with the expression

In document Python - How to Program (Page 172-174)

sequences of values.

Line 13 accesses a particular dictionary value, using the [] operator Dictionary values are accessed with the expression

dictionaryName[ key ]

In line 13, the dictionaryName is grades and the key is the string "Steve". This expres- sion evaluates to the value stored in the dictionary at key "Steve", namely, 76. Line 14 assigns a new value, 90, to the key "Steve". Dictionary values are modified using syntax similar to that of modifying lists. Line 15 prints the result of changing the dictionary value. Line 18 inserts a new key-value pair into the dictionary. Although this statement resembles the syntax for modifying an existing dictionary value, it inserts a new key-value pair because Michael is a new key. The statement

dictionaryName[ key ] = value

modifies the value associated with key, if the dictionary already contains that key. Other- wise, the statement inserts the key-value pair into the dictionary.

Software Engineering Observation 5.1

When adding a key-value pair to a dictionary, mis-typing the key could be a source of inad-

vertent errors. 5.1

Lines 19–20 print the results of adding a new key-value pair to the dictionary. The order in which the key-value pairs are printed is entirely arbitrary (remember that a dictio- nary is an unordered collection of key-value pairs).

16

17 # add to an existing dictionary 18 grades[ "Michael" ] = 93

19 print "\nDictionary grades after modification:"

20 print grades 21

22 # delete entry from dictionary 23 del grades[ "John" ]

24 print "\nDictionary grades after deletion:"

25 print grades

The value of emptyDictionary is: {}

All grades: {'Edwin': 89, 'John': 87, 'Steve': 76, 'Laura': 92} Steve's current grade: 76

Steve's new grade: 90

Dictionary grades after modification:

{'Edwin': 89, 'Michael': 93, 'John': 87, 'Steve': 90, 'Laura': 92} Dictionary grades after deletion:

{'Edwin': 89, 'Michael': 93, 'Steve': 90, 'Laura': 92}

Fig. 5.9 Fig. 5.9 Fig. 5.9

The expression dictionaryName[ key ] can lead to subtle programming errors. If this expression appears on the left-hand side of an assignment statement and the dictionary does not contain the key, the assignment statement inserts the key-value pair into the dictionary. However, if the expression appears to the right of an assignment statement (or any statement that simply attempts to access the value stored at the specified key), then the statement causes the program to exit and to display an error message, because the program is trying to access a nonexistent key.

Common Programming Error 5.4

Attempting to access a nonexistent dictionary key is a “key error”, a runtime error. 5.4 Line 23 deletes an entry from the dictionary. The statement

del dictionaryName[ key ]

removes the specified key and its value from the dictionary. If the specified key does not exist in the dictionary, then the above statement causes the program to exit and to display an error message. Again, this is because the program is accessing a nonexistent key. This runtime error can be caught through exception handling, which we discuss in Chapter 12.

Dictionaries are powerful data types that help programmers accomplish sophisticated tasks. Many Python modules provide data types similar to dictionaries that facilitate access and manipulation of more complex data. In the next section, we explore the dictionary’s capabilities further.

5.6 List and Dictionary Methods

We have seen how sequences and dictionaries enable programmers to accomplish high-lev- el data manipulation, such as storing and retrieving data. We now introduce a new program- ming concept, the method, to extend data-manipulation capabilities.

As discussed in Chapter 2, Introduction to Python Programming, all Python data types contain at least three properties: a value, a type and a location. Some Python data types (e.g., strings, lists and dictionaries) also contain methods. A method is a function that performs the behaviors (tasks) of an object. In this section, we discuss list and dictionary methods; we dis- cuss string methods inChapter 13, Strings Manipulation and Regular Expressions.

List methods implement several behaviors, such as appending a value to the end of a list or determining the index of a particular element in the list. The program of Fig. 5.10 appends items to the end of a list, using a list method. The program asks the user to enter the names of Shakespearean plays and appends the names to a list.Line 4 creates an empty list,playList, to store the names of the plays entered by the user.The forstructure (lines 8–10) uses list methodappendto append items to the end of variable playList.

Methodappendtakes as an argument the new element to insert at the end of the list. To invoke the list method, specify the name of the list, followed by the dot (.)access operator, followed by the method call (i.e., method name and necessary arguments). Lines 14–15 define another for loop that prints the names of the user-entered Shakespearean plays. Notice that line 15 uses the - formatting character to left align the names.

Figure 5.10 demonstrates how a data type’s methods provide a way for programmers to create applications that perform useful data-manipulation tasks. Figure 5.11 uses another list method to perform a more typical data-manipulation task—counting the number of times a

particular value occurs in a list. Lines 4–7 create a list (responses)that contains several values between 1–10. Lines 11–12 contain a for loop that calls list methodcountto return the amount of times an element appears in a list.Method count takes as an argument a value of any data type. If the list contains no elements with the specified value, method count

returns 0. Lines 11–12 print the frequency of each value in the list. 1 # Fig. 5.10: fig05_10.py

2 # Appending items to a list. 3

4 playList = [] # list of favorite plays 5

6 print "Enter your 5 favorite Shakespearean plays.\n"

7

8 for i in range( 5 ):

9 playName = raw_input( "Play %d: " % ( i + 1 ) ) 10 playList.append( playName )

11

12 print "\nSubscript Value"

13

14 for i in range( len( playList ) ):

15 print "%9d %-25s" % ( i + 1, playList[ i ] ) Enter your 5 favorite Shakespearean plays.

Play 1: Richard III

In document Python - How to Program (Page 172-174)