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


years_dictionary.py 2/2

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

FILENAME="data/years.dat"

lastNameToClassYear = {}

namesFile = open(FILENAME, "r")

for line in namesFile:
    # add each line (as a mapping) to the dictionary
    dataList = line.split()
    lastName = dataList[0]
    year = dataList[1]
    lastNameToClassYear[lastName] = year
    
namesFile.close()

# display the mappings, in order by last name
sortedLastNames = list(lastNameToClassYear.keys())
sortedLastNames.sort()

for lastName in sortedLastNames:
    print("%18s %3s" % (lastName, lastNameToClassYear.get(lastName)))
    


Generated by GNU enscript 1.6.4.