Asix3

MIT Pset8 Problem 1 dict syntax

Feb 3rd, 2012
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. def loadSubjects(filename):
  2.     """
  3.    Returns a dictionary mapping subject name to (value, work), where the name
  4.    is a string and the value and work are integers. The subject information is
  5.    read from the file named by the string filename. Each line of the file
  6.    contains a string of the form "name,value,work".
  7.  
  8.    returns: dictionary mapping subject name to (value, work)
  9.    """
  10.  
  11.     # The following sample code reads lines from the specified file and prints
  12.     # each one.
  13.     inputFile = open(filename)
  14.     subDict = {}
  15.     for line in inputFile:
  16.         lSplit = string.split(string.strip(line),',')
  17.         subDict[lSplit[0]] [VALUE] = (int(lSplit[1]),int(lSplit[2]))
  18.     return subDict
  19.  
  20.     # TODO: Instead of printing each line, modify the above to parse the name,
  21.     # value, and work of each subject and create a dictionary mapping the name
  22.     # to the (value, work).
  23.  
  24. def printSubjects(subjects):
  25.     """
  26.    Prints a string containing name, value, and work of each subject in
  27.    the dictionary of subjects and total value and work of all subjects
  28.    """
  29.     totalVal, totalWork = 0,0
  30.     if len(subjects) == 0:
  31.         return 'Empty SubjectList'
  32.     res = 'Course\tValue\tWork\n======\t====\t=====\n'
  33.     subNames = subjects.keys()
  34.     subNames.sort()
  35.     for s in subNames:
  36.         val = subjects[s][VALUE] ## What is this syntax?
  37.         work = subjects[s][WORK] ## What is this syntax?
  38.         res = res + s + '\t' + str(val) + '\t' + str(work) + '\n'
  39.         totalVal += val
  40.         totalWork += work
  41.     res = res + '\nTotal Value:\t' + str(totalVal) +'\n'
  42.     res = res + 'Total Work:\t' + str(totalWork) + '\n'
  43.     print res
Advertisement
Add Comment
Please, Sign In to add comment