Contents
- ascii_dictionary.py
- reportAvgData.py
- using_dictionary.py
- years_dictionary.py
ascii_dictionary.py 1/4
[top][prev][next]
# Demonstrate use of dictionary, using ASCII values
# By Sara Sprenkle
# create an empty dictionary
charToAscii = {}
ordValue = ord('a')
while ordValue <= ord('z'):
# add mapping to dictionary of chr(ordValue) --> ordValue (ordinal value)
char = chr(ordValue)
charToAscii[char] = ordValue
ordValue += 1
print(charToAscii)
print(sorted(charToAscii))
# demonstrate what happens if you try to look up a value that doesn't exist
print( charToAscii.get('!') )
print( charToAscii['!'] )
reportAvgData.py 2/4
[top][prev][next]
# Computes the average high temperature from multiple locations.
# Each location has an associated file that contains the daily
# high temperatures for last year at one location.
# Writes a report about the data in the form:
# <locationname> <avgtemp>
# <locationname> <avgtemp>
# ...
#
# Average temperature should be displayed to two decimal places
# Not covered in class
# By CSCI111
DATA_DIR = "data/"
LOCATIONS = ["alaska", "florida", "virginia"]
DATA_EXT = ".dat"
SUMMARY_FILE_NAME = "all_locations.dat"
def main():
outFile = open("data/report.dat", "w")
for location in LOCATIONS:
dataFileName = DATA_DIR + location + DATA_EXT
avgTemp = calculateAvgTemp(dataFileName)
print("The average temperature in {:s} is {:.2f}".format(location, avgTemp))
outFile.write( "{:s} {:.2f}\n".format(location, avgTemp))
outFile.close()
def calculateAvgTemp( datafileName ):
"""
Given the name of the data file formatted such that there is a
temperature on each line of the file, calculates and returns
the average of all the temperatures in the file as a float
"""
# open the file
dataFile = open( datafileName, "r")
tempSum = 0
numTemps = 0
# read the file, line by line
for line in dataFile:
# convert the line to a float --> temperature
temperature = float(line)
# accumulate the temperatures
tempSum = tempSum + temperature
# accumulate the number of lines in the file
numTemps += 1
# close the file
dataFile.close()
# calculate the average
average = tempSum/numTemps
# return the average
return average
main()
using_dictionary.py 3/4
[top][prev][next]
# Demonstrate use of dictionary using book index
# by Sara Sprenkle
# create an empty dictionary
topicToPageNumber = {}
# add entries to the dictionary
topicToPageNumber["integer"] = 20
topicToPageNumber["list"] = 60
topicToPageNumber["string"] = 45
topicToPageNumber["dictionary"] = 58
topicToPageNumber["float"] = 25
print("~~~~ topicToPageNumber dictionary: ~~~~~~")
# iterates through the keys in the dictionary
for topic in topicToPageNumber:
# print the key and its associated value
print(topic, topicToPageNumber[topic])
print()
# display the type that is returned by dictionary methods
print("type of dictionary.keys():", type(topicToPageNumber.keys()))
print("type of dictionary.values():", type(topicToPageNumber.values()))
print("The number of keys is", len(topicToPageNumber.keys()))
# iterate through the values
print("\nIterate through the values:")
for val in topicToPageNumber.values():
print(val)
print("\nLook at the keys:")
keyList = list(topicToPageNumber.keys())
print("as <dict_keys>:\n", topicToPageNumber.keys())
print("as a list:\n", keyList)
print("\nPrint dictionary alphabetically by keys:")
# printing in order by key
keysSorted = list(topicToPageNumber.keys())
keysSorted.sort()
for topic in keysSorted: # alternative: sorted(keysSorted)
# print the key and its associated value
print(topic, topicToPageNumber[topic])
print("\nPrint dictionary alphabetically by keys, again, in a different way:")
for topic in sorted(topicToPageNumber):
print(topic, topicToPageNumber[topic])
print("\nWhat happens if you try to access a key that doesn't exist?")
# demonstrate what happens if you try to look up a value that doesn't exist
print( "Using get:", topicToPageNumber.get('anothertopic') )
print( "Using indexing:", topicToPageNumber['anothertopic'] )
years_dictionary.py 4/4
[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")
# create our accumulator dictionary
nameToYear = {}
# go through each line
for line in yearsFile:
# split at the space into the name and the year
rosterList = line.split()
# key is the name, value is the year
name = rosterList[0]
year = rosterList[1]
# add mapping into the dictionary
nameToYear[name] = year
# Alternatively but not as readable: nameToYear[ rosterList[0] ] = rosterList[1]
yearsFile.close()
print(nameToYear)
#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 nameToYear:
year = nameToYear[studentName]
print(studentName, "is expected to graduate in", year)
else:
print(studentName, "is not on the roster")
Generated by GNU Enscript 1.6.6.