#---------------------------------------------------------------------- # Motivation for dictionaries #---------------------------------------------------------------------- #---------------------------------------------------------------------- # WITHOUT DICTIONARIES #---------------------------------------------------------------------- # Remember Lab 1? We did something like the following: def Process (Name,Score): # Do something fun with Name and Score, like: print (Name, Score) return def Main1(): Process("Fred",78) Process("Sam",34) Process("Mary",98) Process("Tom",57) return # This is not an efficient approach, because # each name and score is "burned in" to the # program. Here's a solution that separates # out the data a little more cleanly, then # the code to run through all the data is more # efficient and much more general: def Main2(): Data = [["Fred",78],["Sam",34],["Mary",98],["Tom",57]] Index = 0 while (Index < len(Data)): Student = Data[Index] # A list of a name and a score Process(Student[0],Student[1]) Index = Index + 1 return # Here's a different way of doing the same thing, since # we really don't need to know *where* in Data each student # is located: def Main3(): Data = [["Fred",78],["Sam",34],["Mary",98],["Tom",57]] for Student in Data: Process(Student[0],Student[1]) return # But what about searching? Here's one approach: def Main4(): Data = [["Fred",78],["Sam",34],["Mary",98],["Tom",57]] Search = input("Enter a student name --- ") Index = 0 Found = False while (Index < len(Data)) and not Found: # Same as: ...and Found == False Student = Data[Index] if Search == Student[0]: print (Student[1]) Found = True # Stop the loop because we found a match else: Index = Index + 1 # Otherwise go to the next item to compare return # Here's a better search: def Main5(): Data = [["Fred",78],["Sam",34],["Mary",98],["Tom",57]] Search = input("Enter a student name --- ") for Student in Data: if Search == Student[0]: print (Student[1]) break # Stops the loop return #---------------------------------------------------------------------- # WITH DICTIONARIES (See: Companion page 250) #---------------------------------------------------------------------- def Main6(): Data = {"Fred":78, "Sam":34, "Mary":98, "Tom":57} Search = input("Enter a student name --- ") if Search in Data: print (Data[Search]) return def Main7(): Data = {"Fred":78, "Sam":34, "Mary":98, "Tom":57} for Name in Data.keys(): Process (Name, Data[Name]) return #----------------------------------------------------------------------