'''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 # Make a new dictionary with some initial data # Words (keys): 'grades', 'gpa', 'school' # Definitions (values): [26, 27, 26], 3.8, 'Colby' '''Accessing keys and values''' # You can access the keys and values from the dictionary # You can convert the keys and values into ordinary lists # 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 = [] # print(keys) # print(values) '''Modifying/adding to a dictionary''' # Examples: set school to Colby College, add a grade, add a key for dorm '''Adding to a dictionary via string variables''' # Example: names-to-GPA lists: # names = ['Bill', 'Carol', 'Ben'] # gpas = [4, 3.8, 3.6] '''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