[Tutor] reading complex data types from text file

bob gailer bgailer at gmail.com
Fri Jul 17 19:48:10 CEST 2009


Chris Castillo wrote:
> how would i go about adding the names to a dictionary as a key and the 
> scores as a value in this code?
>
>
# refactored for better use of Python, correct logic, and flow

scores = {} # empty dictionary
total = 0
for line in open("bowlingscores.txt", "r"):
    if line.strip().isdigit():
        score = int(line)
        scores[name] = score
        total += score
    else:
        name = line.strip()
averageScore = total / len(scores)
fileOut = open("bowlingaverages.txt", "w")
fileOut.write("Bowling Report\n" + ("-" * 50) + "\n")
for name, score in scores.items():
   if score == 300:
       score = "\tPerfect score!"
   elif score < averageScore:
       score = "\tBelow average"
   elif score > averageScore:
       score = "\tAbove average!"
   else:
       score = "\tAverage!"
   print name, score

-- 
Bob Gailer
Chapel Hill NC
919-636-4239


More information about the Tutor mailing list