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