def rankings(filename,school): d = {} f = open(filename) for line in f: parts = line.split(":") prof = parts[1] dept = parts[2] rank = float(parts[3]) if parts[0] == school: key = (prof,dept) if key not in d: d[key] = [] d[key].append(rank) # (name,school) : [1,2,3,4] for key in d: d[key] = sum(d[key])/len(d[key]) # now sort the tuples (name,dept,ranking) # first create the tuples, then sort them tups = [(t[0],t[1],d[t]) for t in d] tups = sorted(tups) # alphabetical by name return sorted(tups, key=operator.itemgetter(2),reverse=True)