# Python Hash Tables # In addition to Array/Lists, Python has a built-in data structure called # 'dictionaries' or 'associative arrays'. Most 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["john smartypants"] = 700123456 # store data indexed by strings. ID["jane fourpointo"] = 700654321 ID["henry deanslist"] = 700111111 # 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["john smartypants"] # prints 700123456 # 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 k in ID.keys(): print ID[k] # prints number associated with each key. # The above loop loops 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.