Contents
- sort_ignore_case.py
- years_dictionary.py
sort_ignore_case.py 1/2
[top][prev][next]
# Example using sort with a key
# Sara Sprenkle
words = ["Washington", "and", "Lee", "computer", "science"]
words.sort()
print("Words in Python str-standard sorted order:")
for word in words:
print(word)
print()
print("Words in sorted order, ignoring upper and lower case:")
# says the key being used to do the sorting: using the str class's
# lower() method.
words.sort(key=str.lower)
for word in words:
print(word)
years_dictionary.py 2/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]
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
# above two lines are equivalent to this:
classYearToNumStudents[classYear] += 1
else:
classYearToNumStudents[classYear] = 1
yearsFile.close()
for classYear in sorted(classYearToNumStudents):
print(classYear, classYearToNumStudents[classYear])
Generated by GNU Enscript 1.6.6.