Python Data Structure Hash Table
Python Data Structure: Hash Tables
A hash table is a data structure in which the address or index value of a data element is generated by a hash function. This makes accessing data faster because the index value acts like a key to the data value. In other words, a hash table stores key-value pairs, but the key is generated by a hash function.
As a result, searching and inserting data elements becomes faster because the key value itself becomes the index into the array storing the data.
In Python, the Dictionary data type represents an implementation of a hash table. Keys in a dictionary must meet the following requirements.
- The keys in a dictionary are hashable, meaning they are generated by a hash function that produces a unique result for each unique value supplied to the hash function.
-
The order of the data elements in a dictionary is not fixed.
So, we see that a hash table is implemented using the dictionary data type below.
Accessing Values in a Dictionary
To access an element in a dictionary, you use the familiar square brackets along with the key to get its value.
Example
# Declare a dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
# Accessing the dictionary with its key
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Output
When the above code is executed, it produces the following output –
dict['Name']: Zara
dict['Age']: 7
Updating a Dictionary
You can update a dictionary by adding a new entry or key-value pair, modifying an existing entry, or deleting an existing entry, as shown in the following simple example.
Example
# Declare a dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # Update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Output
When the above code is executed, it produces the following output –
dict['Age']: 8
dict['School']: DPS School
Deleting Dictionary Elements
You can delete individual dictionary elements or clear the contents of an entire dictionary. You can also delete an entire dictionary in one operation. To explicitly delete an entire dictionary, use the del statement.
Example
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict; # delete entire dictionary
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Output
This produces the following output. Note that an exception is raised because after del dict, dictionary no longer exists.
dict['Age']: dict['Age']
dict['School']: dict['School']