Hash Tables, better known as Hash Maps, are just collections of key-value pairs. In other words, they are pieces of data (values) mapped to unique identifiers called properties (keys).
Hash Maps were designed to give us a way of, given a key, associating a value with it for very quick lookups.
In Python, the Hash Map is implemented as a dictionary. This is why adding and lookup in a dictionary is so fast.
If you've worked with dictionaries in the past, you were working with Hash Maps without knowing it.
Creation:
You create an empty Hash Map just by creating an empty dictionary, like this:
hashMap = {}
Creating an empty dictionary takes O(1) time.
Initialization:
You can also add some key-value pairs in your dictionary at creation:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown'
}
Accessing values:
A value is retrieved from a dictionary by specifying its corresponding key in square brackets ([]):
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown'
}
# Accessing values:
print(person['name']); # "Andy"
print(person['age']); # 30
# Accessing non-existing key:
print(person['job']); # raises a KeyError exception
As you can see, if you refer to a key that is not in the dictionary, Python raises a KeyError exception.
Accessing a value from a dictionary takes O(1) time.
Adding an entry:
Adding an entry to an existing dictionary is simply a matter of assigning a new key and value, via the assignment operator:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown'
}
# Adding new entries:
person['job'] = 'Teacher'
str = 'hobby'
person[str] = 'Fishing'
print(person)
# The new Hash Map:
# {
# 'name': 'Andy',
# 'age': 30,
# 'hair color': 'brown',
# 'job': 'Teacher',
# 'hobby': 'Fishing'
# }
Adding a new entry to a dictionary takes O(1) time.
Updating an entry:
If you want to update an entry, you can just assign a new value to an existing key:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown'
}
# Updating entries:
person['name'] = 'Andrew'
person['age'] = 29
print(person)
# The new Hash Map:
# {
# 'name': 'Andrew',
# 'age': 29,
# 'hair color': 'brown'
# }
Updating an entry from a dictionary takes O(1) time.
Deleting entries:
The del operator allows you to remove a key from a dictionary:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown',
'hobby': 'Fishing'
}
# Deleting entries:
del person['name']
key = 'age'
del person[key]
# Deleting a non-existent entry:
# del person['job'] -> this would raise a KeyError exception
print(person)
# The new Hash Map:
# {
# 'hair color': 'brown',
# 'hobby': 'Fishing'
# }
If you try to delete a key that is not in the dictionary, Python raises a KeyError exception.
Deleting an entry from a dictionary takes O(1) time.
Checking if a key exists:
You can check if a key exists in a dictionary using the in operator:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown',
'hobby': 'Fishing'
}
key = 'age'
print(key in person) # True
print('job' in person) # False
Iterating over the dictionary keys:
If we want to iterate over keys of the dictionary, we can use the for loop along with the keys() method:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown',
'hobby': 'Fishing'
}
for key in person.keys():
print(key + ' is ' + str(person[key]))
# This will print the following:
# hobby is Fishing
# age is 30
# hair color is brown
# name is Andy
Notice the order is not the same as initiated. Dictionary keeps the data in random order
Also Notice that we used str() to cast / convert the value into a string since we have the integer 30 which needs casting. If we don't use it, we will get a runtime error
Iterating over a dictionary takes O(n) time.
Iterating over the dictionary values:
If we want to iterate over values of the dictionary, we can use the for loop along with the values() method:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown',
'hobby': 'Fishing'
}
for val in person.values():
print(val)
# This will print the following:
# Fishing
# 30
# brown
# Andy
Notice the order is not the same as initiated. Dictionary keeps the data in random order
Iterating over a dictionary takes O(n) time.
Iterating using both the key and the value for simplicity:
If we want to iterate over both keys and values of the dictionary, we can use the for loop along with the items() method:
person = {
'name': 'Andy',
'age': 30,
'hair color': 'brown',
'hobby': 'Fishing'
}
for key, val in person.items():
print(key + ' is ' + str(val))
# This will print the following:
# hobby is Fishing
# age is 30
# hair color is brown
# name is Andy
Notice the order is not the same as initiated. Dictionary keeps the data in random order
Also Notice that we used str() to cast / convert the value into a string since we have the integer 30 which needs casting. If we don't use it, we will get a runtime error
Iterating over a dictionary takes O(n) time.
Assignment
Follow the Coding Tutorial and let's play with some dictionaries.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.
