Page 191 -
P. 191

surfers with their scores


                        Code Magnets Solution

                        You were to rearrange the code magnets at the bottom of the page
                        to complete the program shown below. Rather than using two
                        arrays, this program stores the results from the surfing contest in a
                        hash:


                                       You need to start with an empty hash,
                                       as opposed to an empty array.


                       scores = {}

                     result_f = open("results.txt")
                     for line in result_f:
                         (name, score) = line.split()
                                                       After splitting out the name and the score, use
                            scores[score] = name       the value of “score" as the key of the hash and

                     result_f.close()                   the value of “name" as the value.
                                                                             You'll find out soon why the “score"
       Use a for loop   print("The top scores were:")                        and not the “name" is used (in this
                                                                             case) as the key of the hash.
       to process the   for each_score in scores.keys():
       contents of
       the hash.             print('Surfer ' + scores[each_score] + ' scored ' + each_score)


                             Display each row from the hash,
                             describing the association.








            Q:   Can I append data to a hash just like I did with an array?  Q:  Can I use anything as the key of a hash?



            A: Yes, and no. There’s no append() method for hashes  A: No, you can’t. The rules Python applies here can be complex
            like the one included with every array. To add a new row of   (as they can be in other programming languages, too). The best
            data to an existing hash, use code similar to that used in the   advice we can give you is to stick with numbers and strings as
            solution, above. Hashes do have their own set of methods, but   keys. Trust us: this isn’t as restrictive as it first sounds and is, by
            append() is not one of them.                    far, the best/easiest strategy to follow.




           156    Chapter 5
   186   187   188   189   190   191   192   193   194   195   196