CS8, Spring 2017

Lab06:
Using Python dictionaries
More list practice


Goals for this lab

By the time you have completed this lab, you and your lab partner should be able to

Step by Step Instructions

Step 0: Get together with your assigned lab partner.

Carefully choose the first pilot. Let the person who has been the pilot least often be the pilot first this time. This lab's pilot should log in and create a lab06 directory under your cs8 folder. You will work in this account for the rest of the lab. If your partner is more than 5 minutes late, ask the TA to pair you with someone else for this week.

Step 1: Bring up IDLE as usual, and open a new window for function definitions

Start IDLE. Then select "File=>New Window" and add a comment at the top of this new file like usual:

# lab06.py
# Name: your name(s), today's date
# grade-point functions using a dictionary and a list

Next, copy the contents of these grade constants and paste into your new file right after the header comment. Then, run your module and save it as lab06.py inside your lab06 directory. You will return to this file soon to create functions, but first some practice.

Step 2: Practice using a Python dictionary

Working in the Python shell window (and assuming you already ran the lab06.py module), use the points dictionary to find out the grade-points associated with a few grades. Remember how you accessed items from a list by typing the list's name with an index number inside the square brackets. With a dictionary you type the value of a key inside the square brackets - the keys for the points dictionary are capitalized letter grade strings like 'A+' and 'B-'. For example:

>>> points['B+']
3.3

If you get an error message saying "NameError: name 'points' is not defined", it means you still need to run the lab06.py module with the grade constants pasted in it. Other errors like "KeyError" or "SyntaxError" or "TypeError" mean you did not type in the expression correctly.

By the way, don't worry if you see some strange-looking results due to the way floating point numbers are stored in the memory. Depending on your system, the results might look like this:

>>> points['B+']
3.2999999999999998

Later in the class we learn how to control the format of such results, but usually we just let the print function gracefully handle it for us:

>>> print(points['B+'])
3.3

Items in a dictionary are key-value pairs. There are three methods that allow access to all of the items: keys() allows access to the keys, values() the values, and items() the key-value pairs as a set of tuples. These methods actually return set-like objects, but you can convert them to lists with the list() function:

>>> list(points.keys())
['A', 'B-', 'D+', 'D-', 'A+', 'C', 'B+', 'C-', 'F', 'A-', 'D', 'C+', 'B']
>>> list(points.values())
[4.0, 2.7, 1.3, 0.7, 4.0, 2.0, 3.3, 1.7, 0.0, 3.7, 1.0, 2.3, 3.0]

And you can iterate to print the items in their natural (dictionary) order. Type in the following for loop, followed by a blank line:

>>> for item in points.items():
	print(item)

Notice the order seems random, but it's not. The dictionary stores the items in a way that it can quickly retrieve them by reference to their keys. To print them in order, usually a programmer sorts on the keys, but that won't work in this particular case:

>>> keys = list(points.keys())
>>> sorted(keys)
['A', 'A+', 'A-', 'B', 'B+', 'B-', 'C', 'C+', 'C-', 'D', 'D+', 'D-', 'F']

So that's why you have the other constant, the list named order. Try printing the points values in order by looping over the items in the list order. And then inside the loop, print the value associated with each grade:

>>> for grade in order:
	print(points[grade])

Step 3: Function to print a table of grade-points

Write a function (in the lab06.py file) named printTable to neatly print a table of the grades and associated grade-points in the customary order. First print column titles "grade" and "points" separated by a tab character ('\t'). Then loop through the grades in order, and print the grade, a tab character, and the associated grade-points.

Here are the first few lines of an example run:

>>> printTable()
grade 	 points
A+ 	 4.0
A 	 4.0

Save the file, and run the module again. Then test your function at the Python prompt to verify it works properly: it should print the entire set of grades (A+ to F), in order and neatly with tabs separating the columns - just like the example above.

Note: If you are having lots of trouble writing this function (or later in Step 4), we suggest you go back to Step 2 for awhile and do some more practicing.

Step 4: Function to calculate grade-point average

Switch roles between pilot and navigator.

Write a function named gpa to calculate and return the grade-point average of a list of grades. The function header should look like this:

def gpa(gradeList):

And here is an example run:

>>> myGrades = ['B+','A-','B', 'A']
>>> gpa(myGrades)
3.5

Step 5: Write test cases

Write a few more test cases - below the function definitions in the lab06.py window - just like you did in the last couple of labs. For each test case: (a) create a list of valid grade strings; (b) print the gpa for this list. Use different lists of varying sizes and be sure to cover the full range of possible grades in your test cases.

Be ready to demo your functions and test cases to a TA.

Step 6: Show off your work and get credit for the lab

Get your TA's attention to inspect your work, and to record your lab completion.

Don't leave early though ... see challenge problems below.

Step 6a. ONLY IF YOU RAN OUT OF TIME TO HAVE THE TA INSPECT YOUR WORK

If you must complete this assignment at CSIL, then submit it with the turnin program. You MUST have both your name and your partner's name in the file in order to receive credit. Remember that the original pilot needs to do this step, since that is whose account you have been using in Phelps 3525.

Bring up a terminal window on CSIL, and cd into the original pilot's cs8 directory, and cd again into the lab06 directory. Then type the following:

turnin Lab06@cs8c lab06.py

Respond "yes" when the program asks if you want to turn in (be sure to read the list of files you are turning in), and then wait for the message indicating success.


Evaluation and Grading

Each student must accomplish the following to earn full credit for this lab:

Optional Extra Challenge

If you finish the lab early or would like an extra challenge

a. Know that dictionary values can be anything, including lists. So a dictionary called grades might have student names as keys, and lists of grades as values:

>>> grades = {'Sue':['A', 'A+', 'A-', 'A-'],
              'Pete':['B-', 'B', 'C+'],
	      'Harvey':['F', 'B+', 'C-']}

Write and test a function named gpaTable that takes a dictionary such as this one as a parameter, and prints a neat table of the grade-point average for each student. For now, don't worry about the order in which the items are printed.

>>> gpaTable(grades)
key 	 gpa
Pete 	 2.66666666667
Harvey 	 1.66666666667
Sue 	 3.85

b. Revise the gpaTable function to print the items in alphabetical order of the keys:

>>> gpaTable(grades)
key 	 gpa
Harvey 	 1.66666666667
Pete 	 2.66666666667
Sue 	 3.85

c. For more dictionary fun, create a dictionary that associates English words (the keys) with associated Pirate phrases (the values). Examples from the text's Programming Exercise 4.3: {'hello':'avast', 'excuse':'arrr', 'sir':'matey', 'madam':'proud beauty', 'officer':'foul blaggart', 'my':'me'} - more are shown on page 153. Then write a function, sayPirate(message), that takes a string as a parameter and returns the string with known words translated to Pirate language (but leaves other words unchanged):

>>> sayPirate("hello sir and madam")
' avast matey and proud beauty'
>>> sayPirate("please excuse my officer")
' please arrr me foul blaggart'

Hint: remember the split() function for strings will create a list of words.

Prepared by Diana Franklin and Michael Costanzo.