# CS111: Dictionary Part 1 Solutions # Task 0. Warm up exercises # Given this backpack dictionary: backpack = { 'money' : 10, 'pencils' : 4, 'umbrella' : True, 'misc': ['lip balm', 'tissues', 'gum'] } # Task A: backpack['misc'] # Task B: backpack['misc'].append('calculator') # Examples of printing options: #---- Option 1:----- # In[]: backpack # Out[5]: # {'misc': ['lip balm', 'tissues', 'gum', 'calculator'], # 'money': 10, # 'pencils': 4, # 'snack': 'flaming hot cheetos', # 'umbrella': True} #---- Option 2:----- # # print backpack # {'money': 10, 'snack': 'flaming hot cheetos', 'umbrella': True, 'misc': ['lip# balm', 'tissues', 'gum', 'calculator'], 'pencils': 4} # # NOTE: order doesn't matter in dictionaries, so items are not ordered # Task C: backpack['snack'] = 'flaming hot cheetos' # Task D: The output looks like this: # for item in backpack: # print item # # money # snack # umbrella # misc # pencils # # When you loop through a dictionary, the KEYS of the dictionary are printed # Task E: if there is more than $5 in your backpack, subtract 5 to buy a snack # if backpack['money'] > 5: # backpack['money'] -= 5 # # OR, EQUIVALENTLY, # # if backpack['money'] > 5: # backpack['money'] = backpack['money'] - 5 # # ............. end warm up exercises ............... # Task 1. Build the cs111 students names and years from nameYear import * from wordlist import * cs111dict = {} for person in nameYear: # person looks like this: ['Kathryn', '2021'] name = person[0] year = person[1] cs111dict[name] = year if __name__ == '__main__': print ('\n\n====== test cs111dict =====') print (cs111dict) print (len(cs111dict)) # 98 # Task 1 def makeYearDict(data): """Returns a dictionary where the keys are graduation year (in strings) and the values are lists of student names with that graduation year""" yearDict = {} # start with an empty dictionary for item in data: # a sample item ['Jennifer', '2020'] # so item[0] is 'Jennifer' and item[1] is '2020' # check to see if year is already a key in dict if item[1] in yearDict: # add name to the end of the list of names yearDict[item[1]].append(item[0]) else: # create a new key:value pair, where the value is a list containing the name yearDict[item[1]] = [item[0]] # very important that this is a LIST return yearDict # so names can be appended to it later