Contents

  1. years_dictionary2.py
  2. years_dictionary.py

years_dictionary2.py 1/2

[
top][prev][next]
# Given a file of the form <firstname> <year>
# creates a mapping between the class year and the number
# of people in that class.
# by CSCI 111

FILENAME="data/roster.dat"

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

# create dictionary
classYearToNumStudents = {}

# read each line of the file
for line in yearsFile:
    # split the line on space
    studentInfoList = line.split()
    
    # extract the classyear from the split line
    classYear = studentInfoList[1]

    # we don't know if the accumulator has been initialized yet
    if classYear in classYearToNumStudents:
    
        # update the accumulator for this class year
        # 1) get the value of the accumulator for the class year
        # 2) update that accumulator's value
        count = classYearToNumStudents[classYear]
        classYearToNumStudents[classYear] = count + 1
    else:
        # this is the first time we've seen this classyear!
        # so, create a new accumulator
        classYearToNumStudents[classYear] = 1
    
    # above two lines are equivalent to this:
    # classYearToNumStudents[classYear] += 1

yearsFile.close()

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
# by CSCI 111

# 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")

# create dictionary
firstNameToClassYear = {}

# read each line of the file
for line in yearsFile:
    # split the line on space
    studentInfoList = line.split()
    
    # extract the first name and classyear from the split line
    firstName = studentInfoList[0]
    classYear = studentInfoList[1]
    
    # add mapping to the dictionary
    firstNameToClassYear[firstName] = classYear

yearsFile.close()

firstNamesList = list(firstNameToClassYear.keys())
firstNamesList.sort()

# display the info -- is it correct?
for firstName in firstNamesList:
    print( firstName, "-->", firstNameToClassYear[firstName] )
    
# display the info -- is it correct?
for firstName in sorted(firstNameToClassYear):
    print( firstName, "-->", firstNameToClassYear[firstName] )

print( len(firstNamesList)) 
# prompt the user for which student they are looking for.

Generated by GNU Enscript 1.6.6.