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
# Sparse commenting (see _annotated version for comments)
# by Sara Sprenkle

# create an empty dictionary
topic_to_page_number = {}

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


print("~~~~ topic_to_page_number dictionary: ~~~~~~")

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


print()

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


# iterate through the values
print("\nIterate through the values:")
for val in topic_to_page_number.values():
    print(val)
    

print("\nLook at the keys:")
key_list = list(topic_to_page_number.keys())
print("as <dict_keys>:\n", topic_to_page_number.keys())
print("as a list:\n", key_list)


print("\nPrint dictionary alphabetically by keys:")
# printing in order by key
sorted_keys = list(topic_to_page_number.keys()) # although, not sorted yet!
sorted_keys.sort()

for topic in sorted_keys:
    # print the key and its associated value
    print(topic, topic_to_page_number[topic])

print("\nPrint dictionary alphabetically by keys, again, in a different way:")
    
for topic in sorted(topic_to_page_number):
    print(topic, topic_to_page_number[topic])
    
print("\n")

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

print("\nWhat happens if you try to access a key that doesn't exist?")
print( "Using get:", topic_to_page_number.get('anothertopic') )

# the following statement will fail and the program exits

print( "Using indexing:",  topic_to_page_number['anothertopic'] )

# we'd never get to this stuff...
print("Never gonna happen")

./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
topic_to_page_number = {}

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


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


print()
print("type of dictionary.keys():", type(topic_to_page_number.keys()))
print("type of dictionary.values():", type(topic_to_page_number.values()))
print("The number of keys is", len(topic_to_page_number.keys()))
print("The number of keys is", len(topic_to_page_number))




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


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



sorted_keys = list(topic_to_page_number.keys()) # although, not sorted yet!
sorted_keys.sort()

for topic in sorted_keys:
    print(topic, topic_to_page_number[topic])

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

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

print("\nWhat happens if you try to access a key that doesn't exist?")
print( "Using get:", topic_to_page_number.get('anothertopic') )

# the following statement will fail and the program exits

print( "Using indexing:",  topic_to_page_number['anothertopic'] )

# we'd never get to this stuff...
print("Never gonna happen")

./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
# by CSCI 111

FILENAME="data/roster.dat"

def main():

    print("This program will tell you in what year a student is expected to graduate.")

    # for testing purposes
    #name_to_year = { "Joey" : 26, "Dawson": 27, "Jen": 28, "Pacey": 29, "Jack": 26}

    name_to_year = createDictionaryFromFile(FILENAME)
    
    # For debugging: display the info -- is it correct?
    print(name_to_year)
    
    while True:
        name = input("What is the student's name? (Hit enter to quit) ")

        if name == "":
            print("Thank you!  Please fill out our customer satisfaction survey to win!")
            break

        if name in name_to_year:
            grad_year = name_to_year[name]
            print(name, "is expected to graduate in", grad_year)
        else:
            print("Sorry, we could not find", name + ".")

    
def createDictionaryFromFile(filename):
    """
    Parses the file named by filename, which is in the form
        name gradyear
        name gradyear
        ...
    Returns a dictionary that maps each name to gradyear
    """
    # initialize our accumulator (dictionary)
    name_to_year = {}
    
    # open file
    year_file = open(filename, "r")
    # repeat reading a line from the file
    for line in year_file:
        # split the line into a list -- default delimiter is a space
        contents = line.split()
        # the first element is the name, the second is the grad year
        name = contents[0]
        grad_year = contents[1]
        
        # add the mapping from the name to the year
        name_to_year[name] = grad_year

    # close file
    year_file.close()
    
    # return dictionary
    return name_to_year

main()





Generated by GNU Enscript 1.6.5.90.