''' ##### Lecture 6 ##### # Michelle Szucs # To download as a Python file, right-click the link # and select "Save link as..." print "Basic dictionary examples" # Creating a dictionary passingDict = {'student1': True, 'student2': False} print "passingDict example 1:", passingDict # We can also add more values passingDict['student3'] = True # You can also put items in the dictionary after you # declare it # Making an empty dictionary passingDict = {} # Adding items to the dictionary passingDict['student1'] = True passingDict['student2'] = False print "passingDict example 3:", passingDict # Keys can only be associated with one value - # the following line of code changes the value # of 'student2' (it doesn't add a second value) passingDict['student2'] = True print "passingDict example 4:", passingDict # Here's how you can access a specific value print "Accessing a value: passingDict['student2'] is", passingDict['student2'] # Trying to access a key that isn't in the # dictionary will result in a KeyError # Uncomment the following line of code to see # the code throw an error #print passingDict['student3'] print # This prints an empty line to separate the code print "Frequency dictionary examples" ''' # As a frequency dictionary # Insert print statements into this function to follow # its flow if you find it confusing def makeFreqDictOne(word): frequency = {} for letter in word: # need to check whether the key exists to # avoid a KeyError # if letter is already a key if letter in frequency: # checks if letter is a key # if it is, increase count by 1 frequency[letter] += 1 # if I haven't added the letter yet else: # add it, make the count 1 frequency[letter] = 1 # This if-else block prevents code from try to access # the value of a key that doesn't exist. return frequency frequencyDict = makeFreqDictOne("Mississippi") print "Original frequency dictionary #1:", frequencyDict ''' # Here's another way of making the frequency dictionary # the "get" method takes two arguments: the key whose value # you want to access, and a value to be returned if a key # error is thrown. # If the key is in the dictionary, its value will be returned. # If the key is not in the dictionary, the second argument # that "get" takes will be returned. # In this case, if the key is in the dictionary, the integer # value it's associated with is returned (the count of that # letter so far). # If the key isn't in the dictionary, 0 is returned. # I then reassign the value associated with the key to the # value produced by get plus one - I'm just incrememnting # the count for that letter. def makeFreqDictTwo(word): frequency = {} for letter in word: frequency[letter] = frequency.get(letter, 0) + 1 return frequency frequencyDict = makeFreqDictTwo("Mississippi") print "Original frequency dictionary #2:", frequencyDict print print "Dictionary functions and tools" # You can delete items from dictionaries using the # del keyword del frequencyDict['i'] print "Removed i:", frequencyDict # The length of a dictionary is the number of # key-value pairs print "Length:", len(frequencyDict) # Some dictionary functions include getting the # keys and getting the values, both returned # as lists print "Keys:",frequencyDict.keys() print "Values:",frequencyDict.values() print print "Dictionaries are mutable, which can cause aliasing problems" ''' # Dictionaries are mutable, which means that they # can be aliased - be careful when changing dictionaries # that have different names but are actually the same # object alias = frequencyDict # The following line is the correct way to copy a dictionary copy = frequencyDict.copy() print "Frequency dictionary:", frequencyDict print "Alias:", alias print "Copy:", copy print "alias['i'] = 3" alias['i'] = 3 print "Frequency dictionary:", frequencyDict print "Alias:", alias print "Copy:", copy print print "Checking multiple elements of a list for truth" ''' # Checking if all items in a list satisfy a certain condition myList = [True, False, True, True] print "List:", myList print "Any:", any(myList) # "or" of the list print "All:", all(myList) # "and" of the list # Using loops and conditionals # I want to return true if every value in the list # is less than 5 def lessThanFive(aList): # You usually need to set a boolean variable to a # initial condition. isLess = True for num in aList: # print statement so we can understand how the # break statement works later on - uncomment # if you're confused #print "num =", num if num >= 5: isLess = False # This break statment makes the for loop # stop once I reach a variable that's not # less than 5. I know I want to return False, # so I might as well save some time and exit early. break return isLess ## THIS IS THE WRONG WAY TO DO IT def lessThanFiveButWrong(aList): isLess = True for num in aList: if num >= 5: return False else: return True ## This function will ONLY check the first item in the list ## THIS IS ALSO WRONG def lessThanFiveButStillWrong(aList): isLess = True for num in aList: if num >= 5: isLess = False else: isLess = True return isLess ## This function will ONLY be affected by the last item # Test cases print print "######### Less than 5 tests ##########" print "Good implementation" print "[1,2,3,4,5,6] (should be False):", lessThanFive([1,2,3,4,5,6]) print "[6,2,3,4,5,1] (should be False):", lessThanFive([6,2,3,4,5,1]) print "[1,2,3,4,-1,3] (should be True):", lessThanFive([1,2,3,4,-1,3]) print "Bad implementation 1" print "[1,2,3,4,5,6] (should be False):", lessThanFiveButWrong([1,2,3,4,5,6]) print "[6,2,3,4,5,1] (should be False):", lessThanFiveButWrong([6,2,3,4,5,1]) print "[1,2,3,4,-1,3] (should be True):", lessThanFiveButWrong([1,2,3,4,-1,3]) print "Bad implementation 2" print "[1,2,3,4,5,6] (should be False):", lessThanFiveButStillWrong([1,2,3,4,5,6]) print "[6,2,3,4,5,1] (should be False):", lessThanFiveButStillWrong([6,2,3,4,5,1]) print "[1,2,3,4,-1,3] (should be True):", lessThanFiveButStillWrong([1,2,3,4,-1,3]) '''