Lab 08, Part 1: Simple dictionaries

Task 1: Create a name:year cs111 dictionary

In your lab08 folder there is a file called nameYear.py that contains a list of 107 fictitious CS111 students and their corresponding graduation year.

Here is a snapshot of what the list looks like (you can open the file in Thonny):

# nameYear.py
nameYear = [
      ...
    ['Sarah', '2024'],
    ['Preedah', '2023'],
       ...
    ['Yujue', '2022'],
    ['Shan', '2024'],

]

Your first task is to create a Python dictionary from this data where the key is the student names and the value is the corresponding years.

Make a new file called simpleDictionaries.py. At the top of the file, import the provided nameYear data:

from nameYear import *

Then, do the following:

  1. Create an empty dictionary called cs111dict.
  2. For each list (student) in nameYear, create a dictionary entry in the cs111dict where the key is the student's name and the value is their year.

Check the results of your work by invoking len(cs111dict)— there should be 101 entries.

Wait a second. Why are there only 101 entries? There are 107 students in our fictitious nameYear.py list! What happened?

Once your cs111dict is built, try out the following statements and describe/discuss the results with your partner:

Task 2: Create a year:[names] CS111 dictionary

Now, using the same nameYear variable, write a function called makeYearDict that returns a dictionary where the keys are the year of graduation and the values are lists of students who will graduate in that year.

Let's say you want to build your dictionary from scratch and we want to add these students:

['Andy', '2021'], ['Sohie', '2024'], ['Peter', '2021']

At this point, our dictionary is empty:

yearDict = { }

Let's take Andy first. His year is 2021. After we add Andy to the dictionary, it looks like this:

yearDict = {'2021': ['Andy'] }

Now we add in Sohie, who has a different year, so that means a new key:value pair.

yearDict = {'2021': ['Andy'],
            '2024': ['Sohie']
              }

And now we add in Peter. Peter will graduate in 2021, so we can add her name to the list associated with the key '2021':

yearDict = {'2021': ['Andy', 'Peter'],
            '2024': ['Sohie']
              }

Hint: remember that each key in a dictionary must be unique. So if the key already exists in your dictionary, then add the name to list associated with that key.

Here is some sample testing code:

# Create the year dictionary
yearDict = makeYearDict(nameYear)
list(yearDict.keys())
# ['2024', '2022', '2023', '2021']  # remember order doesn't matter
yearDict['2022'] 
# ['Angela', 'Rumi', 'Helen', 'Lisa', 'Yujue', 'Maya', 'Ting']
yearDict['2021'] 
# ['Lena', 'Andrea', 'Amal', 'Ronghao', 'Alexandra', 'Rebecca', 'Rebecca', 'Jocelyn', 'Bryant', 'Claire']
len(yearDict['2024'])
# 57
len(yearDict['2023']) 
# 33

Table of Contents