'''lecture_34_dictionaries.py Showcase what dictionaries are and how to work with them Oliver W. Layton CS 151: Computational Thinking: Visual Media Fall 2020 ''' '''Dictionaries Works like a physical dictionary or address book: you look up a definition ("value") using a WORD ("key") Different from a list where you look up a value using an INDEX. ''' # Make a new empty dictionary # myDict = {} # Make a new dictionary with some initial data # Words (keys): 'grades', 'gpa', 'school' # Definitions (values): [26, 27, 26], 3.8, 'Colby' # student = {'grades': [26, 27, 26], 'gpa': 3.8, 'school': 'Colby'} # print(student['grades']) # print(student['gpa']) '''Accessing keys and values''' # You can access the keys and values from the dictionary # print(student.keys()) # print(student.values()) # You can convert the keys and values into ordinary lists # keylist = list(student.keys()) # print(keylist[1]) # You can loop through keys or values (without converting to lists first) # Example, loop through keys and values, append each to a list # keys = [] # values = [] # for key in student.keys(): # keys.append(key) # print(keys) # for value in student.values(): # values.append(value) # print(values) # You can loop through both at the same time using the items method # for key, value in student.items(): # print('key is', key, '| value is', value) '''Modifying/adding to a dictionary''' # Examples: set school to Colby College, add a grade, add a key for dorm # student['student'] = 'Colby College' # print(student) # student['grades'].append(21) # print(student) # student['dorm'] = 'Taylor' # print(student) '''Adding to a dictionary via string variables''' # Example: names-to-GPA lists: # names = ['Bill', 'Carol', 'Ben'] # gpas = [4, 3.8, 3.6] # for i in range(len(names)): # myDict[names[i]] = gpas[i] # print(myDict) '''Checking if a key is in the dictionary''' # Program will crash if you try to access a key that doesn't exist, so it is a good idea to check # for it before accessing # if 'year' in student: # print(student['year'])