Page 201 -
P. 201

process the parameter


                        Code Magnets Solution

                        You were to rearrange the code magnets to complete the function required. The following
                        functionality is implemented:
                        1. Accept a single parameter (the surfer ID).
                        2. Process the data file one line at a time, creating a hash from the line on each iteration.
                        3. Compare the parameter against the ID read from the file.
                        4. If the IDs match, return the hash to the caller.
                        5. If no match is found, return an empty hash to the caller.






                                                                 Open the file so that you

                   def find_details(id2find):                    can read the data.
                         surfers_f = open("surfing_data.csv")

          Use “for" to
         loop through      for each_line in surfers_f:
         each of the lines                Make sure the hash starts out empty.
         in the file.        s = {}
                             (s['id'], s['name'], s['country'], s['average'], s['board'],
                                            s['age']) = each_line.split(";")
        Check if the ID      if id2find == int(s['id']):                   Cut up the line (using split()) and
        supplied as a parameter                                            assign the data to the hash (using
        is the same as the one                                             multiple-assignment).
                               surfers_f.close()
        read from the file.                        You have a match! So, close
                                 return(s)         the file then return the
                                                    current hash to the caller.
                       surfers_f.close()


                        return({})
                                                                                         Load this!
                                You processed the entire
                                file but found NO MATCH.
                                Close the file and return an
                                empty hash.
                                                                   Download surfing_data.csv from
                                                                   the Head First Programming website before
                                                                   continuing. Be sure to put the file in the
                                                                   same directory/folder as your code.



           166    Chapter 5
   196   197   198   199   200   201   202   203   204   205   206