How To Initialize Hashmap In Python

In this tutorial, we will learn how to initialize a Hashmap in Python. A hashmap, also known as a dictionary in Python, is a data structure that stores key-value pairs. Dictionaries are useful when we need to store and retrieve data quickly based on a specific key.

We will walk through the different ways to initialize a dictionary and how to perform basic operations such as adding and removing elements, looping through keys and values, and more.

Step 1: Creating an Empty Dictionary

To create an empty dictionary, simply use curly braces {} or the dict() constructor.

Output:

{}
{}

Step 2: Initializing a Dictionary with Key-Value Pairs

We can also initialize a dictionary with key-value pairs by placing them inside curly braces {} and separating keys and values with colons.

Output:

{'name': 'John', 'age': 25, 'city': 'New York'}

Step 3: Adding Elements to a Dictionary

We can add new key-value pairs to a dictionary by specifying the key in square brackets [] and assigning a value to it.

Output:

{'name': 'John', 'age': 25, 'city': 'New York', 'country': 'USA'}

Step 4: Removing Elements from a Dictionary

We can remove an element from a dictionary by using the del keyword, followed by the key of the element we want to remove.

Output:

{'name': 'John', 'age': 25, 'country': 'USA'}

Step 5: Looping Through Keys and Values in a Dictionary

We can iterate through the keys and values of a dictionary using a for loop with the items() method, which returns a list of the dictionary’s key-value pairs represented as tuples.

Output:

name: John
age: 25
country: USA

Step 6: Initializing a Dictionary Using Comprehensions

We can also conveniently create a dictionary using dictionary comprehensions, a concise way to generate dictionaries based on existing iterables.

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Now that we’ve explored different ways to initialize and work with dictionaries, let’s see the full code example in one place.

Full Code

Conclusion

In this tutorial, we learned how to initialize dictionaries (hashmaps) in Python and perform basic operations such as adding, removing, and looping through key-value pairs. Implementing dictionaries in Python makes it easy to create and manage a mapping of keys to associated values, allowing us to improve our code efficiency and readability.