What is a hash table in Python?

Hash tables are a form of data structure in which a hash function is used to produce the address or index value of a piece of data. Since the index value acts as a key for the data value, you can access the data faster. In other words, a hash table contains key-value pairs, but the key is created using a hashing function. As a result, a data element’s search and insertion functions become considerably faster, since the key values themselves become the index of the array that holds the data.

The dictionary data type in Python is used to implement hash tables. The dictionary’s keys meet the following criteria:

  • The dictionary’s keys are hashable, which means they’re created using a hashing function that produces a unique result for each unique value sent to it.
  • In a dictionary, the order of data elements is not fixed.

Code

How to access values in a dictionary

To get the value of a dictionary entry, you may use the standard square brackets ([]) with the key.

# Declare a dictionary
dict = {'Name': 'Srija', 'Age': 15,'Loc': 'Hyd'}
#Access the dictionary with its key
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

How to update a dictionary

You can add a new entry or key-value combination to a dictionary and change an existing entry.

# Declare a dictionary
dict = {'Name': 'Srija', 'Age': 15,'Loc': 'Hyd'}
dict['Age'] = 16; # update existing entry
dict['School'] = 'DAV PUBLIC School'; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']

How to delete dictionary elements

You can either delete individual items or erase the entire content of a dictionary. You can even remove the full content all at once. Use the del command to delete the entire content.

dict = {'Name': 'Srija', 'Age': 15,'Loc': 'Hyd'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

Free Resources