Imagine you want to store and quickly find phone numbers by name. You have two options: use a list of pairs (name, number) or a hash map. Why is a hash map better for this?
Think about how long it takes to find an item in a list versus a hash map.
A hash map uses a special function to jump directly to the data, making lookups very fast. A list requires checking each item one by one, which is slower.
Look at this Python code that uses a dictionary to store ages by name. What will it print?
ages = {'Alice': 30, 'Bob': 25, 'Charlie': 35}
print(ages['Bob'])Check the value stored for the key 'Bob'.
The dictionary stores 'Bob' with value 25, so printing ages['Bob'] outputs 25.
Consider this Python code:
data = {'x': 10, 'y': 20}
print(data['z'])What will be the result?
What happens if you ask for a key that does not exist in a Python dictionary?
Accessing a missing key in a Python dictionary raises a KeyError because the key is not found.
Imagine you have thousands of items and want to find one quickly by a unique key. How does a hash map help compared to a list?
Think about how a hash function converts a key into an index.
A hash map uses a hash function to compute an index from the key, allowing direct access to the item without scanning the entire collection.
You need to store user profiles identified by unique usernames. You want to quickly add, find, and update profiles by username. Which data structure is best?
Consider which structure supports fast lookup by a unique key.
A hash map stores data by keys and allows very fast add, find, and update operations using the key, making it ideal for user profiles by username.