# Python Hash Tables # In addition to Array/Lists, Python has a built-in data structure called # 'dictionaries' or 'associative listts'. Many computer scientists however, # will call these structures "hash tables". An array indexes its elements # using integers. But often we wish to store data by some other attribute. # For example, suppose I want a data strucutres that stores the 700 id # numbers of the students. I want to be able to look up a 700 number given # a student's name. An array is not really appropriate for this kind of # structure, but a hash table is: ID = {} # creates an empty hash table (or 'dictionary') # can also say ID = dict(), which creats a dict() object, {} is shortcut. # ID's of famous Hofstra students: ID["John Milker"] = 701654321 ID["Jane Grazer"] = 702123456 # The string used to "index" the hash table ID is called the "key". To # access the data stored in the table I need to know the key. print(ID["Jane Grazer"]) # prints 702123456 # It's also possible to define an entire table by giving each key:value pair: H = {'A':1, 'B':2, 'C':3} print( H['B'] ) # will print 2 # Looping through a hash table: I can't use the while loops like with arrays # becaue the elements are not numbered 0,1,2,3... anymore. Instead, I have # to use the following kinds of for-loops: for x in H: print(x,":",H[x]) # Don't use indexes on these lists. The following is a similar loop. for k in H.keys(): print(k,H[k]) # prints number associated with each key. # The above loop iterates through every key and associated value in the table. # Here's a similar loop for key,value in ID.items(): print (key,":", value) # prints each key-value pair. # Usually hash tables are indexed by strings, but they can also be indexed # by any kind of immutable data. # Like arrays, these structures are MUTABLE. Mutability means you have to be # aware that the variable assigned to a dictionary is actually a pointer, and that # mutliple pointers can be pointing to the same data. H['B'] = 4 # changes the contents that H points to. #### How to handle non-existent keys. # If you write H['D'], you should expect an error, just as when you try to access an # array index that doesn't exist. To be sure that a key exists before accessing it, # so as to avoid the error, you can do one of the following. # 1. Use Python's None value. Python has a reserved value None that represents .. # nothing. Don't confuse None with False or with 0. Instead of of H['D'], you can # also use H.get('D'), which will return None if the value doesn't exist. You can # test if None was returned with if H.get('D')==None: ... # 2. Use "exception handling". You can wrap the code that may result in an error # in "try-except" block: try: print(H['D']) except: print("nothing") # If an exception occurs between try: and except:, it will instead execute the code # under except. This has the same effect as: if H.get('D')!=None: print(H['D']) else: print("nothing") # 3. Check if the key exists first, though this can be inefficient: if 'D' in H.keys(): print(H['D']) else: print("nothing")