Contents
- ascii_dictionary.py
- years_dictionary2.py
- years_dictionary.py
ascii_dictionary.py 1/3
[top][prev][next]
# Demonstrate use of dictionary, using ASCII values
# CS111
ascii= {}
x = ord('a')
while x <= ord('z'):
ascii[chr(x)] = x
x+=1
print ascii
years_dictionary2.py 2/3
[top][prev][next]
# Read in years from a file and put into a dictionary.
# CS111
YEARSFILE="data/years.dat"
yearsData = file(YEARSFILE, "r")
# create an empty dictionary that will map last names to years
yearToCount={}
for line in yearsData:
line = line.strip()
# FIRST " " SPLITS NAME AND YEARS
spacePos = line.find(" ")
if spacePos== -1:
print "Error: no name/year pair in line:", line
else:
name = line[:spacePos]
# print "name=", name
year = line[spacePos+1:]
# print "year=", year
if yearToCount.get(year) != None:
# same as: if year in yearToCount :
yearToCount[year]+=1
else:
yearToCount[year]=1
yearsData.close()
for year in yearToCount:
count = yearToCount[year]
if count > 1:
print "There are", count, year + "s."
else:
print "There is 1", year + "s."
years_dictionary.py 3/3
[top][prev][next]
# Read in students' name and years from a file and put into a dictionary.
# CS111
YEARSFILE="data/years.dat"
yearsData = file(YEARSFILE, "r")
# create an empty dictionary that will map last names to years
nameToYear={}
for line in yearsData:
line = line.strip()
# FIRST " " SPLITS NAME AND YEARS
spacePos = line.find(" ")
if spacePos== -1:
print "Error: no name/year pair in line:", line
else:
name = line[:spacePos]
# print "name=", name
year = line[spacePos+1:]
# print "year=", year
# map the last name to the year
nameToYear[name]=year
yearsData.close()
# print nameToYear
# Note what order these are printed in ...
# Is it the same as what was in the original data file?
for name in nameToYear:
print name, "is a", nameToYear[name]
# not actually sorted at this point
sortedKeys = nameToYear.keys()
sortedKeys.sort()
print "\nIn sorted order: "
for name in sortedKeys:
print name, "is a", nameToYear[name]
Generated by GNU enscript 1.6.4.