dictionary hash
hash function
data structures
Python programming
coding basics

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.

Practice algorithms

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:

h:U[0,m1]h: U \rightarrow [0, m-1]

Where:

  • hh is the hash function.
  • UU is the universe of possible keys.
  • mm is the number of slots (or buckets) in the hash table.

Mechanics of Hashing in Dictionaries

  1. Key-Value Mapping: Each key is hashed to produce a hash value, which maps to an index where the corresponding value is stored.
  2. Collision Handling: Collisions are inevitable because of the limited bucket size. Python handles collisions using a technique known as open addressing, specifically probing.
  3. 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
Course
Intermediate
27 lessons
15 hours
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 course
Track 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.

Practice algorithms

All Rights Reserved.