A dictionary is an unordered collection of key-value pairs where each key must be unique. It allows for quick lookups, insertions, and deletions of elements based on their keys. Python's dictionary uses a hash table under the hood to achieve efficient data retrieval.
Here's how you can use a hash map (dictionary) in Python:
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}
my_dict = dict(apple=1, banana=2, orange=3)
my_dict = dict([('apple', 1), ('banana', 2), ('orange', 3)]) Accessing elements in the hash map:
print(my_dict['apple']) # Output: 1
print(my_dict.get('banana')) # Output: 2 print(my_dict.get('grape', 'Not found')) # Output: 'Not found' (default value for missing key) Adding or updating elements in the hash map:
my_dict['grape'] = 4
my_dict['banana'] = 5 Deleting elements from the hash map:
del my_dict['orange']
removed_value = my_dict.pop('banana') Checking if a key exists in the hash map:
if 'apple' in my_dict: print("Apple exists!") Iterating through the hash map:
for key in my_dict: print(key, my_dict[key])
for key, value in my_dict.items(): print(key, value) It's important to note that dictionaries in Python maintain insertion order starting from Python 3.7 and are fully ordered in Python 3.8+. Before Python 3.7, dictionaries were unordered collections.