Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 1
Назад: Making an Efficient Hash Table
Дальше: Hash Tables for Speed

Hash Tables for Organization

Because hash tables keep data in pairs, they’re useful in many scenarios for organizing data.

Some data exists naturally in paired form. The fast-food menu and thesaurus scenarios from this chapter are classic examples. The menu contains each food item paired with its price. The thesaurus contains each word paired with its synonym. In fact, this is why Python refers to hash tables as dictionaries. A dictionary is a common form of paired data; it’s a list of words with their respective definitions.

Other examples of naturally paired data can include tallies, such as political candidates and the number of votes each received:

 {​"Candidate A"​: 1402021, ​"Candidate B"​: 2321443, ​"Candidate C"​: 432}

An inventory tracking system, which keeps track of how much of each item is in supply, is another tally example:

 {​"Yellow Shirt"​: 1203, ​"Blue Jeans"​: 598, ​"Green Felt Hat"​: 65}

Hash tables are such a natural fit for paired data that we can even use them to simplify conditional logic in certain instances.

Say we encounter a function that returns the meaning of common HTTP status code numbers:

 def​ ​status_code_meaning​(number):
 if​ number == 200:
 return​ ​"OK"
 elif​ number == 301:
 return​ ​"Moved Permanently"
 elif​ number == 401:
 return​ ​"Unauthorized"
 elif​ number == 404:
 return​ ​"Not Found"
 elif​ number == 500:
 return​ ​"Internal Server Error"

If we think about this code, we’ll realize that the conditional logic revolves around paired data, namely, the status code numbers and their respective meanings.

By using a hash table, we can completely eliminate the conditional logic:

 status_codes = {200: ​"OK"​, 301: ​"Moved Permanently"​,
  401: ​"Unauthorized"​, 404: ​"Not Found"​,
  500: ​"Internal Server Error"​}
 
 
 def​ ​status_code_meaning​(number):
 return​ status_codes.get(number)

Another common use for hash tables is to represent objects that have various attributes. For example, here’s a representation of a dog:

 {​"name"​: ​"Fido"​, ​"breed"​: ​"Pug"​, ​"age"​: 3, ​"gender"​: ​"Male"​}

As you can see, attributes are a kind of paired data, since the attribute name becomes the key, and the actual attribute becomes the value.

We can create an entire list of dogs if we place multiple hash tables inside an array:

 [
  {​"name"​: ​"Fido"​, ​"breed"​: ​"Pug"​, ​"age"​: 3, ​"gender"​: ​"Male"​},
  {​"name"​: ​"Lady"​, ​"breed"​: ​"Poodle"​, ​"age"​: 6, ​"gender"​: ​"Female"​},
  {​"name"​: ​"Spot"​, ​"breed"​: ​"Dalmatian"​, ​"age"​: 2, ​"gender"​: ​"Male"​}
 ]
Назад: Making an Efficient Hash Table
Дальше: Hash Tables for Speed