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:
1 |
hash_map = {"key1": "value1", "key2": "value2", "key3": "value3"} |
Example:
1 |
student_grades = {"Alex": 95, "Mary": 87, "John": 92} |
You can also create an empty dictionary like this:
1 |
empty_dict = {} |
Step 2: Accessing Values in a Hashmap
To access the value associated with a specific key in a Hashmap, use the following syntax:
1 |
hash_map["key"] |
Example:
1 2 |
student_grades = {"Alex": 95, "Mary": 87, "John": 92} print(student_grades["Mary"]) |
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:
1 |
hash_map["key"] = "new value" |
Example:
1 2 3 4 |
student_grades = {"Alex": 95, "Mary": 87, "John": 92} student_grades["Nina"] = 88 student_grades["Mary"] = 89 print(student_grades) |
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.
1 |
del hash_map["key"] |
Example:
1 2 3 |
student_grades = {"Alex": 95, "Mary": 87, "John": 92} del student_grades["Mary"] print(student_grades) |
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.
1 2 3 4 |
if "key" in hash_map: # key exists in the dictionary else: # key does not exist in the dictionary |
Example:
1 2 3 4 5 |
student_grades = {"Alex": 95, "Mary": 87, "John": 92} if "Mary" in student_grades: print("Mary's grade:", student_grades["Mary"]) else: print("Mary's grade not found.") |
Output:
Mary's grade: 87
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
student_grades = {"Alex": 95, "Mary": 87, "John": 92} print(student_grades["Mary"]) student_grades["Nina"] = 88 student_grades["Mary"] = 89 print(student_grades) del student_grades["Mary"] print(student_grades) if "Mary" in student_grades: print("Mary's grade:", student_grades["Mary"]) else: print("Mary's grade not found.") |
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.