Hashmap in python

Vedant Kumar
5 min readAug 12, 2021

Implementing Hashmap in Python and comparing it with other languages

Hey There again. In today’s article, we will cover what hashmap is, how is it called in different languages, and finally, how is it used in Python language. So without any further adieu, let’s dive straight into the introduction.

Introduction

In simple words, hashmaps can be thought of as a currency. Now, every currency or note has a value attached to it. The note also has its unique identity code. Let’s call this unique id a key. This key will hold some value for the currency. So, in order to determine the value of the currency, one must know the key number and only then, the value of the currency will be fetched. Hashmaps operate in a similar fashion.

Hashmaps stores data in these key and value pairs. One object is used as a key to determining the value of another object. On insertion of the same key twice, the most recent insertion is stored, or the value of the key is replaced with the most recent edition. Hashmaps are unsynchronised. It means any addition or deletion of (key, value) pairs are done in a random manner. Also, there can only exist one null key in hashmaps. On the contrary, multiple null values can exist.

Parameters

As mentioned previously, two parameters constituting hashmaps, and they are:

Key: unique entry

Value: values mapped to the key

Implementation in Java

In Java, the HashMap class can be found within java.util package. Hashmap implements the Map interface and extends AbstractMap class.

Let’s take a small example to better understand how Hashmap operates in Java. We will consider a Hashmap that has the keys representing the name of the animal and the values representing the type of the animal. And both of these will have a string data type. To instantiate a Hashmap in Java, we will use the following command:

HashMap<String, String> animals = new HashMap<String, String>();

The above line of code creates a hashmap that allows two entries of the string data type.

To add keys and values, the following commands can be used:

animals.put(“Shiro”, “Dog”);
animals.put(“Yoru”, “mouse”);
animals.put(“Doraemon”, “Cat”);

The one that we type in first is the key and the string following that is the value.

Hashmaps support various functionalities, such as:

  1. View a value of the key by typing animals.get(“Shiro”). This will return a string value Dog.
  2. Similarly, to remove an entry from the hashmap, you can use the command animals.remove(“Shiro”). This will remove the Shiro, Dog pair from the hashmap.
  3. Moving on, to clear the entire hashmap or to remove all the pairs, clear() method can be used. For example, animals.clear().
  4. Finally, to get the size of the hashmap, animals.size() can be used.

Moving on to Python

Till now, we have covered what hashmaps look like and their implementation in Java. Now moving to Python. In Python, Hash Tables or Hashmaps are implemented through a built in dictionary. As the name suggests, a dictionary is made up of various (key, value) pair elements. Just like in the dictionary every word has its definition, so is the case of dictionaries in Python. A simple example of a dictionary can be a mapping of student names with their roll number or mapping employee names with their respective employee ID. Also, the elements of dictionary are not ordered and they are mutable. That means they can be changed — insert, delete, clear.

Initialising/creating dictionaries in Python

There are two ways in which we can instantiate a dictionary in Python. They are the following:

  1. Using curly braces ({})
  2. Using dict() function

Let’s look at the first method.

my_dict={‘Shiro’ : ‘Dog’ , ‘Yoru’: ‘mouse’ , ‘Doraemon’: ‘Cat’}

The above line of command creates a dictionary my_dict that has the above entries. The length of the dictionary is 3 and has the type of a dictionary(can be found by using the command — type(my_dict)).

Similarly, using the dict() command, a dictionary can be initialized. For example,

new_dict = dict()

type(new_dict)

The above lines of code creates a dictionary new_dict and returns a type dictionary.

If we want to make a dictionary similar to the one with the previous method, all we have to do is write -

my_dict=dict(Shiro = ‘Dog’ , Yoru = mouse’ , Doraemon = Cat’)

The above command creates a dictionary similar to

my_dict={‘Shiro’ : ‘Dog’ , ‘Yoru’: ‘mouse’ , ‘Doraemon’: ‘Cat’}

Simple! isn’t it?

Now that we have covered how to instantiate or make a dictionary, let’s dive into some operations that we can perform using dictionaries.

Access values in a dictionary

Using Key values:

Values in a dictionary can be accessed by typing the name of the dictionary followed by key name inside a square box. For example, my_dict[‘Shiro’] will return a value of Dog. Similarly, my_dict[‘Yoru’] will return a value of mouse, so on and so forth.

Using functions:

Another way of accessing the values of a dictionary is by using various in built functions. For example,

For a dictionary below

my_dict={‘Shiro’ : ‘Dog’ , ‘Yoru’: ‘mouse’ , ‘Doraemon’: ‘Cat’}

The command my_dict.keys() will print all the present keys in the dictionary. In this case, we will get Shiro, Yoru, and Doraemon as the output.

Similarly, my_dict.values() will return all the values of respective keys in the dictionary. In this case, we will get Dog, mouse, and Cat as the output.

Finally, we can also access values using get() command. For example, my_dict.get(‘Shiro’) will return the value Dog.

Using loops

Loops are another way of accessing values in a dictionary by iterating over them. Again, let’s take an example of the previous dictionary itself, that is,

my_dict={‘Shiro’ : ‘Dog’ , ‘Yoru’: ‘mouse’ , ‘Doraemon’: ‘Cat’}

Let’s iterate over this dictionary,

for i in my_dict:

print(i)

The above lines of code prints all the keys present in the dictionary.

for i in my_dict.values():

print(i)

The above lines of code prints all the values associated with keys in the dictionary.

And lastly,

for i,j in my_dict.items():

print(i,j)

The above lines of code prints both the key as well as values of all the entries present in the dictionary.

Update values of a dictionary

Dictionaries are mutable, which means their entries can be updated as and when required. For example, if I want to change the animal type of Shiro from Dog to Lion, I can do it in the following ways:

my_dict[‘Shiro’] = ‘Lion’

Furthermore, an entirely new entry can also be added in the following way.

my_dict[‘Omen’] = ‘Tiger’

The newly updated my_dict will now look like this:

{‘Shiro’ : ‘Dog’ , ‘Yoru’: ‘mouse’ , ‘Doraemon’: ‘Cat’ , ‘Omen’: ‘Tiger’ }

Delete entries of a dictionary

Deleting entries in a dictionary can be achieved in multiple ways. For example, to delete an entire entry or a key and value pair, we can use the following line of code.

del my_dict[‘Shiro’]

The above line deletes the Shiro and Dog entry from the dictionary.

To remove only the value and not the key, we can make use of pop() function.

my_dict.pop(‘Shiro’)

The above line pops the value of the key Shiro and retains the key element. You must be wondering what value mus the key Shiro be holding now? Currently, it maps to a null value.

There is also a way to remove the last entered element in the dictionary. It can be achieved using popitem() function.

Finally, to completely clear off the dictionary of its entries we can use the clear() function.

my_dict.clear() clears the dictionary clean so that it has no entries.

Thank you!

--

--