Contents

  1. using_dictionary.py
  2. years_dictionary.py

using_dictionary.py 1/2

[
top][prev][next]
# Demonstrate use of dictionary, using ASCII values
#

# create an empty dictionary
ascii= {}

x = ord('a')

while x <= ord('z'):
    # add mapping to dictionary of chr(x) --> x (ordinal value)
    char = chr(x)
    ascii[char] = x
    x+=1

# iterates through the keys in the dictionary
for letter in ascii:
    # print the key and its associated value
    print(letter, ascii[letter])

# display the type that is returned by dictionary methods
print(type(ascii.keys()))
print(type(ascii.values()))
print("The number of keys is", len(ascii.keys()))

# iterate through the values
print("Iterate through the values:")
for val in ascii.values():
    print(val)
    
keyList = list(ascii.keys())
print("as <dict_keys>:\n", ascii.keys())
print("as a list:\n", keyList)

# printing in order by key
keysSorted = list(ascii.keys())
keysSorted.sort()

for letter in keysSorted: 
    # print the key and its associated value
    print(letter, ascii[letter])

#alternative to above solution, printing in order by key    
for letter in sorted(ascii):
    # print the key and its associated value
    print(letter, ascii[letter])


years_dictionary.py 2/2

[
top][prev][next]
# Given a file of the form <lastname>,<class>
# creates a mapping between the last names and class
# by CSCI 111

FILENAME="data/years.dat"

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

lastnameToClass = {}

for line in yearsFile:
    # remove the new line from the end of the line
    line = line[:-1] 
    
    # split the line on commas
    # after class, I changed the data file to separate the
    # last name from the class year by commas.
    dataList = line.split(",")
    
    # get the lastname
    lastname = dataList[0]
    
    # get the class year
    classYear = dataList[1]
    
    # add the mapping from the lastname --> class year
    lastnameToClass[lastname] = classYear

yearsFile.close()    

#print(lastnameToClass)
    
#for lastname in sorted(lastnameToClass):
#    print(lastname, lastnameToClass[lastname])

userLastName = input("Give me a last name, and I'll tell you their year (press enter to quit): ")

while userLastName != "":
    # make sure the last name is in our dictionary
    if userLastName in lastnameToClass:
        userClassYear = lastnameToClass[userLastName]
        print(userLastName, "is a", userClassYear)
    else:
        print(userLastName, "is not a valid last name")
    
    userLastName = input("Give me a last name, and I'll tell you their year (press enter to quit): ")

Generated by GNU Enscript 1.6.6.