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:
To get the value of a dictionary entry, you may use the standard square brackets ([]) with the key.
# Declare a dictionarydict = {'Name': 'Srija', 'Age': 15,'Loc': 'Hyd'}#Access the dictionary with its keyprint "dict['Name']: ", dict['Name']print "dict['Age']: ", dict['Age']
You can add a new entry or key-value combination to a dictionary and change an existing entry.
# Declare a dictionarydict = {'Name': 'Srija', 'Age': 15,'Loc': 'Hyd'}dict['Age'] = 16; # update existing entrydict['School'] = 'DAV PUBLIC School'; # Add new entryprint "dict['Age']: ", dict['Age']print "dict['School']: ", dict['School']
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 dictdel dict ; # delete entire dictionary