Hashing a dictionary?
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Hashing is a critical concept in computer science, especially in data structures like hash tables. It is a technique that computes a fixed-size number (hash value or hash code) from variable-length input data. This hash value is typically a numeric value that helps in high-speed data retrieval. In Python, dictionaries (also known as associative arrays or hash maps) utilize hashing as a core mechanism to store and access data efficiently. Let's delve into how hashing works for dictionaries.
How Hashing Works
`Hash` Function
A hash function is an essential component of a hash table. It takes an input (or key) and returns an index in an array. A good hash function minimizes the occurrence of collision—a scenario where two different keys produce the same hash value.
The mathematical representation of a hash function is:
Where:
- is the hash function.
- is the universe of possible keys.
- is the number of slots (or buckets) in the hash table.
Mechanics of Hashing in Dictionaries
- Key-Value Mapping: Each key is hashed to produce a hash value, which maps to an index where the corresponding value is stored.
- Collision Handling: Collisions are inevitable because of the limited bucket size. Python handles collisions using a technique known as open addressing, specifically probing.
- Load Factor: This is the ratio of the number of elements to the size of the hash table. Python dynamically resizes the dictionary to maintain efficient operation as the number of elements grows.
Simplified Example
Imagine a simple dictionary with keys as strings and values as integers:
- Hashing 'apple': The string 'apple' is passed to a hash function, and it computes an index like `2`.
- Storing the value: The dictionary stores `10` at index `2`.
- Searching: When accessing `my_dict['apple']`, Python hashes the key, finds index `2`, and retrieves the value `10`.
Related reading

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.