'''lecture_24_dictionaries.py Showcase what dictionaries are and how to work with them Oliver W. Layton CS 151: Computational Thinking: Visual Media Spring 2021 ''' '''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 = {} # print(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) # print('The student\'s grades are:', student['grades']) '''Accessing keys and values''' # You can access the keys and values from the dictionary theKeys = student.keys() # print(theKeys) theValues = student.values() # print(theValues) # You can convert the keys and values into ordinary lists keyList = list(student.keys()) # print(keyList) # print(keyList[0]) valueList = list(student.values()) # print(valueList) # 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:', key, '| value:', value) '''Modifying/adding to a dictionary''' # Examples: set school to Colby College, add a grade, add a key for dorm print(student) student['school'] = 'Colby College' # print(student) # student['grades'] = [26, 27, 26, 30] student['grades'].append(30) 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] myDict = {} for i in range(len(names)): myDict[names[i]] = gpas[i] print('Dictionary:', 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 # myDict['hi'] = 'there' if 'hi' in myDict: print(myDict['hi']) else: print('its not in there.')