Contents

  1. years_dictionary2.py
  2. years_dictionary.py

years_dictionary2.py 1/2

[
top][prev][next]
# Given a file of the form <firstname> <classyear>,
# report how many students are in each class year
# by CSCI 111

FILENAME="data/roster.dat"

# open the file for reading
yearsFile = open(FILENAME, "r")

# maps the grad year to its count (the number of people graduating in that year)
# --> this is a dictionary of accumulators!!!
gradYearToCount = {}
# for each line in the file
for line in yearsFile:
    # split the line into the two elements
    nameAndGradYearList = line.split()
    gradYear = nameAndGradYearList[1]
    
    # is this gradYear already in my dictionary?
    if gradYear in gradYearToCount:
        # if it is, add to its count
        gradYearToCount[gradYear] += 1
        # gradYearToCount[gradYear] = gradYearToCount[gradYear] + 1
    # else, create a new mapping of the grad year to the accumulator with a value of 1
    else:
        gradYearToCount[gradYear] = 1
    
yearsFile.close()   
print(gradYearToCount)

years_dictionary.py 2/2

[
top][prev][next]
# Given a file of the form <firstname> <class>
# creates a mapping between the first names and class
# (In progress...)
# by CSCI 111

FILENAME="data/roster.dat"

# open the file for reading
yearsFile = open(FILENAME, "r")

nameToGradYear = {}
# for each line in the file
for line in yearsFile:
    # split the line into the two elements
    nameAndGradYearList = line.split()
    name = nameAndGradYearList[0]
    gradYear = nameAndGradYearList[1]
    # add the student name as the key and the grad year as the value
    nameToGradYear[name] = gradYear
    
yearsFile.close()   
print(nameToGradYear)

print("This program will repeatedly prompt you for a")
print("student's first name and tell you their graduation year.")
print("It stops if you enter nothing for a name.")

#repeatedly (until the user enters nothing)
while True:
    # prompt for the student name and display their class year
    studentName = input("What is the student's name? ")
    
    if studentName == "":
        break
    
    if studentName in nameToGradYear:
        print( studentName, "is expected to graduate in", nameToGradYear[studentName])
    else:
        print(studentName, "was not found")

    if nameToGradYear.get(studentName) == None:
        print(studentName, "was not found")
    else:
        print( studentName, "is expected to graduate in", nameToGradYear.get(studentName))

Generated by GNU Enscript 1.6.6.