EX06 - Dictionary Functions


In this exercise you will get some practice with some dictionary functions.

Assignment Outline

  • invert (Level: Novice) – 30 Points Autograded
    • Unit Tests – 5 Points Autograded
  • favorite_colors (Level: Advanced) – 35 Points Autograded
    • Unit Tests – 5 Points Autograded
  • count (On Your Own) – 15 Points Autograded
    • Unit Tests – 5 Points Autograded
  • Style, Linting, Typing – 20 Points Autograded

Note: Even if your functions are not 100% correct or finished, you can get full credit for the unit tests if you set up a function skeleton and write your tests assuming correct functionality.

0. Pull the skeleton code

You will find the starter files needed by “pulling” from the course workspace repository. Before beginning, be sure to:

  1. Be sure you are in your course workspace. Open the file explorer and you should see your work for the course. If you do not, open your course workspace through File > Open Recent.
  2. Open the Source Control View by clicking the 3-node (circles) graph (connected by lines) icon in your sidebar or opening the command palatte and searching for Source Control.
  3. Click the Ellipses in the Source Control pane and select “Pull” from the drop-down menu. This will begin the pulling process from the course repository. It should silently succeed.
  4. Return to the File Explorer pane and open the exercises directory. You should see it now contains another directory named ex06. If you expand that directory, you should see the starter file for the three functions you’ll be writing.
  5. If you do not see the ex06 directory, try once more but selecting "Pull From" and select upstream in step 2.

1. invert – 30 Points

This is the first function you will write in dictionaries.py. The other two functions will also be defined in this file.

Given a dictionary of [str, str], invert should return a dict[str, str] that inverts the keys and the values. The keys of the input list becomes the values of the output list and vice versa.

Remember that keys in a dictionary are unique. If you encounter more than one of the same key when trying to invert your dictionary, i.e., raise a KeyError. Example usage:

>>> invert({'a': 'z', 'b' : 'y', 'c': 'x'})
{'z': 'a', 'y': 'b', 'x': 'c'}
>>> invert({'apple': 'cat'})
{'cat': 'apple'}
>>> invert({'kris': 'jordan', 'michael': 'jordan'})
KeyError

Similar to how you raised a ValueError in the max function for list utils, the syntax for raising a KeyError is: `raise KeyError(“error message of your choice here!”)

2. favorite colors – 35 Points

Create a function in your dictionaries.py file called favorite_color. It has the following specifications:

  1. It has one parameter, of type dict[str, str] of names and favorite colors.
  2. It returns a str which is the color that appears most frequently.
    1. If there is a tie for most popular color, return the color that appeared in the dictionary first.

You can also check the correctness of your favorite_color function by calling it in main, printing the result, then running the program with the same command from above.

An example:

The results of which would look like:

$ python -m exercises.ex06.favorite_color
blue

3. count ON YOUR OWN – 15 Points

Given a list[str], this function will produce a dict[str, int] where each key is a unique value in the given list and each value associated is the count of the number of times that value appeared in the input list.

  • Function name: count
  • Parameter: list[str] - list of values to count the frequencies of
  • Return Type: dict[str, int] - a dictionary of the counts of each of the items in the input list

Implementation strategy:

  1. Establish an empty dictionary to store your built-up result in
  2. Loop through each item in the input list
    1. Check to see if that item has already been established as a key in your dictionary. Try the following boolean conditional: if <item> in <dict>: – replacing <item> with the variable name of the current value and <dict> with the name of your result dictionary.
    2. If the item is found in the dict, that means there is already a key/value pair where the item is a key. Increase the value associated with that key by 1 (counting it!)
    3. If the item is not found in the dict, that means this is the first time you are encountering the value and should assign an initial count of 1 to that key in the result dictionary.
  3. Return the resulting dictionary.

4. Unit Tests

For each function from above (invert, favorite_color, count), you are to define at least 3x unit test functions. Remember that a unit test function starts with test_. In order for our grader to execute correctly, import these functions using the complete path. This should look like exercises.ex06.dictionaries import invert, favorite_color, count.

The 3 unit tests should consist of:

  • One edge case
  • Two use cases

Include descriptive function names and docstrings like we saw in class on Tuesday so that it captures what is being tested.

The command to run your tests is python -m pytest exercises/ex06 or you can run them using the beaker tab in VSCode if it is working (it tends to be a bit flaky).

If your screen is large enough, you are encouraged to open these files side-by-side in VSCode by dragging the tab of one to the right side of VSCode so that it changes to a split pane view. Closing your file explorer can help give you additional horizontal space.

Optional Testing for KeyError:

You may optionally add a test for the invert function to check if the KeyError is being raised. Testing errors requires different syntax than testing normal outputs. If an error is raised then the function never actually returned anything, so we are unable to assert a return value. Instead try the following:

  1. Make sure to import pytest
  2. Use the following code as an example:

5. Make a Backup Checkpoint “Commit”

As you make progress on this exercise, making backups is encouraged.

  1. Open the Source Control panel (Command Palette: “Show SCM” or click the icon with three circles and lines on the activity panel).
  2. Notice the files listed under Changes. These are files you’ve made modifications to since your last backup.
  3. Move your mouse’s cursor over the word Changes and notice the + symbol that appears. Click that plus symbol to add all changes to the next backup. You will now see the files listed under “Staged Changes”.
    • If you do not want to backup all changed files, you can select them individually. For this course you’re encouraged to back everything up.
  4. In the Message box, give a brief description of what you’ve changed and are backing up. This will help you find a specific backup (called a “commit”) if needed. In this case a message such as, “Progress on Exercise 3” will suffice.
  5. Press the Check icon to make a Commit (a version) of your work.
  6. Finally, press the Ellipses icon (…), look for “Pull/Push” submenu, and select “Push to…”, and in the dropdown select your backup repository.

5. Submit to Gradescope for Grading

Login to Gradescope and select the assignment named “EX06 - Dictionaries.”. You’ll see an area to upload a zip file. To produce a zip file for autograding, return back to Visual Studio Code.

If you do not see a Terminal at the bottom of your screen, open the Command Palette and search for “View: Toggle Integrated Terminal”.

Type the following command (all on a single line):

python -m tools.submission exercises/ex06

In the file explorer pane, look to find the zip file named “21.mm.dd-hh.mm-exercises-ex06.zip”. The “mm”, “dd”, and so on, are timestamps with the current month, day, hour, minute. If you right click on this file and select “Reveal in File Explorer” on Windows or “Reveal in Finder” on Mac, the zip file’s location on your computer will open. Upload this file to Gradescope to submit your work for this exercise.

Autograding will take a few moments to complete. If there are issues reported, you are encouraged to try and resolve them and resubmit. If for any reason you aren’t receiving full credit and aren’t sure what to try next, come give us a visit in office hours!

Contributor(s): Kaki Ryan