How To Use Hashmap In Python

In this tutorial, we will discuss how to use Hashmap in Python. Hashmap is a data structure that stores key-value pairs. In Python, the concept of Hashmap is implemented using dictionaries.

Dictionaries are mutable and unordered. The key-value pairs in a Hashmap are separated by commas and enclosed within curly brackets {}. A key-value pair in a Hashmap consists of a key and its corresponding value, separated by a colon (:).

Step 1: Creating a Hashmap (Dictionary)

To create a Hashmap in Python, you can use the following syntax:

Example:

You can also create an empty dictionary like this:

Step 2: Accessing Values in a Hashmap

To access the value associated with a specific key in a Hashmap, use the following syntax:

Example:

Output:

87

Step 3: Adding or Updating Key-Value Pairs in a Hashmap

Adding a new key-value pair or updating the value of an existing key in a Hashmap is simple. Use the following syntax:

Example:

Output:

{'Alex': 95, 'Mary': 89, 'John': 92, 'Nina': 88}

Step 4: Delete a Key-Value Pair from a Hashmap

You can use the del keyword to remove a key-value pair from the dictionary.

Example:

Output:

{'Alex': 95, 'John': 92}

Step 5: Check if a Key Exists in a Hashmap

To check if a key exists in a Hashmap, use the in keyword.

Example:

Output:

Mary's grade: 87

Full Code

Conclusion

In this tutorial, we covered the basics of using Hashmap in Python using dictionaries. We learned how to create, access, add, update, delete, and check for the existence of key-value pairs in a Hashmap. Hashmaps are useful for solving various programming problems that require efficient storage and retrieval of data using unique keys.