Contents

  1. ./ascii_dictionary.py
  2. ./using_dictionary_annotated.py
  3. ./using_dictionary.py
  4. ./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('z')

while ordValue >= ord('a'):
    # 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['!'] )

print("We don't get to here.")

./using_dictionary_annotated.py 2/4

[
top][prev][next]
# Demonstrate use of dictionary using book index
# by Sara Sprenkle

topicToPageNumber = {}

# add entries to the dictionary
topicToPageNumber["integer"] = 20
topicToPageNumber["list"] = 60
topicToPageNumber["string"] = 35
topicToPageNumber["dictionary"] = 58
topicToPageNumber["float"] = 20


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:
    # 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("\n")
print("Using get for 'list':", topicToPageNumber.get("list"))
print("Using indexing for 'list':", topicToPageNumber["list"])

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'] )

./using_dictionary.py 3/4

[
top][prev][next]
# Demonstrate use of dictionary using book index
# Sparse commenting (see _annotated version for comments)
# by Sara Sprenkle

# create an empty dictionary
topicToPageNumber = {}

# add entries to the dictionary
topicToPageNumber["integer"] = 20
topicToPageNumber["list"] = 60
topicToPageNumber["string"] = 35
topicToPageNumber["dictionary"] = 58
topicToPageNumber["float"] = 20


print("~~~~ topicToPageNumber dictionary: ~~~~~~")
for topic in topicToPageNumber:
    print(topic, topicToPageNumber[topic])


print()
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()))
print("The number of keys is", len(topicToPageNumber))




for val in topicToPageNumber.values():
    print(val)
    


keyList = list(topicToPageNumber.keys())
print("as <dict_keys>:\n", topicToPageNumber.keys())
print("as a list:\n", keyList)



keysSorted = list(topicToPageNumber.keys())
keysSorted.sort()

for topic in keysSorted:
    print(topic, topicToPageNumber[topic])

for topic in sorted(topicToPageNumber):
    print(topic, topicToPageNumber[topic])
    
print("\n")

print("Using get for 'list':", topicToPageNumber.get("list"))
print("Using indexing for 'list':", topicToPageNumber["list"])

print("\nWhat happens if you try to access a key 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"

def main():

    nameToYear = { "Joey" : 24, "Dawson": 23, "Jen": 25, "Pacey": 26, "Jack": 24}
    #nameToYear = createDictionaryFromFile(FILENAME)
    
    # TODO: display the info -- is it correct?
    
    print("This program will repeatedly prompt you for a")
    print("student's first name and tell you their graduation year.")
    print("It stops if you enter nothing for a name.")
    
    #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
    
def createDictionaryFromFile(filename):
    """
    Parses the filename, which is in the form
        name gradyear
        name gradyear
        ...
    Returns a dictionary that maps each name to gradyear
    """
    # open the file for reading
    yearsFile = open(filename, "r")
    
    
    
    yearsFile.close()

Generated by GNU Enscript 1.6.5.90.