Lessons › coding and computer science · taught by Leo
Dictionaries and hash maps: keys, values, collisions
Learn what dictionaries store, how hash maps find values quickly, and how collisions are handled.
Learn this with Leo, freeA voiced lesson with a live whiteboard, quizzes and a tutor you can call, at tutelage.appWhat a dictionary stores
Think of a dictionary like an address book. You look up one thing and get one matching thing back.
In code, the first thing is the key, and the second thing is the value.
Together, they make pairs. That is the whole idea.
Why hash maps are fast
A hash map uses a hash function to turn a key into a spot in memory quickly.
It uses a hash function to jump near the right spot instead of searching from the start.
That is why lookups are usually very fast, close to one step on average.
Predict the lookup result
In a dictionary, if 'cat' maps to 7, what do you get for the key 'cat' ?
- 7
- cat
- Nothing always
Show answer
7: Yes. You use the key to find its value.
Worked example: build a map
Let’s build a tiny map from fruit names to numbers.
First, each key gets sent through a hash function. That gives a place to store it.
Then the value is stored with that key’s slot. So pear ends up matched with 4.
Now when we ask for pear, the map goes straight to that pair and returns 4.
What happens next?
A hash map has the key 'bird' already stored. What should the map do first when you ask for 'bird' ?
- Use the hash function to find the spot
- Start checking every key in order
- Sort all the keys first
Show answer
Use the hash function to find the spot: Exactly. First hash the key to find the likely spot.
Why collisions can happen
Two different keys can land in the same spot. That is called a collision.
A good hash map has a plan for that, like storing a small list in the same bucket.
So collisions do not break the map. They are just something the map must handle.
Pick the collision idea
What is a collision in a hash map?
- Two keys land in the same spot
- A key has no value
- The map forgets everything
Show answer
Two keys land in the same spot: Yes. Two different keys end up mapped to the same location.
How to use a dictionary
Here is the simple flow to remember.
Start with the key, because the key is what you search by.
Then hash it, go to the spot, and read the value.
Your turn: choose the key
Which part is usually the key in a student dictionary?
- student ID number
- the grade itself
- the teacher's desk
Show answer
student ID number: Correct. The student ID is a good key because it identifies one student.
Recap: the 4-step loop
Use this checklist on your own.
One: start with the key.
Two: hash it and find the bucket. Three: handle collisions if needed. Four: return the value.