Table of Contents

    Hash Table / Dictionary

    Chapter 18.6

    Hash Table / Dictionary in Data Structures

    Learn what a hash table or dictionary is, how key-value storage works, why hashing is useful, how data can be inserted, searched, updated, and deleted quickly, and how hash tables are used in real-world programming problems.

    Introduction

    A hash table is an important data structure used to store data in the form of key-value pairs. It allows programs to find, insert, update, and delete data very quickly when a unique key is available.

    In many programming languages, a hash table is also known by different names such as dictionary, map, hash map, or associative array. Although the name may be different, the main idea is the same: store a value with a key and retrieve the value using that key.

    For example, in a student management system, we can store student records using roll numbers as keys. If we know the roll number, we can quickly find the student details without checking every student one by one.

    "A hash table stores data as key-value pairs and allows fast access to values using unique keys."

    Simple Definition of Hash Table / Dictionary

    A hash table or dictionary is a data structure that stores data using a unique key and its related value. The key is used to quickly find the value.

    In simple words:

    • A hash table stores data in key-value pairs.
    • Each key is unique.
    • Each key points to a value.
    • The value can be found quickly using the key.
    • It is useful for fast lookup and searching.
    • It is commonly used in real-world applications.
    HASH TABLE CONCEPT
    Hash Table = Key + Value + Fast Lookup
    Important: A hash table is useful when we want to search data using a unique identifier, such as student roll number, employee ID, product code, username, or email address.

    Why Do We Need Hash Tables?

    Hash tables are needed because searching data in a normal list or array can become slow when the number of records becomes large. If we store thousands of student records in a list, finding one student may require checking many records one by one.

    A hash table solves this problem by using a key. Instead of searching through all records, the program directly uses the key to locate the value. This makes hash tables very efficient for lookup-based problems.

    Without Hash Table

    • Searching may require checking each item one by one.
    • Lookup becomes slow for large data.
    • Finding records by ID becomes inefficient.
    • Code may require repeated loops.
    • Duplicate handling may become harder.
    • Large record systems become difficult to manage efficiently.

    With Hash Table

    • Data can be found quickly using a key.
    • Lookup becomes efficient.
    • Records can be organized by unique identifiers.
    • Code becomes cleaner and easier to manage.
    • Duplicate keys can be controlled.
    • Large systems can handle data more efficiently.

    Prerequisites

    Before learning hash tables or dictionaries, students should understand some basic programming and data structure concepts.

    Prerequisite Topic Why It Is Needed
    Variables To understand how values are stored and referenced.
    Arrays / Lists To compare sequential storage with key-value storage.
    Objects To understand structured data and property-based access.
    Loops To process all key-value pairs when needed.
    Conditional Statements To check whether a key exists before accessing or updating data.
    Functions / Methods To create operations such as add, get, update, delete, and search.
    Basic Searching Concept To understand why hash tables improve lookup performance.

    Real-World Analogy of Hash Table

    A hash table can be compared to a contact list on a mobile phone. In a contact list, a person's name or phone number can be used to quickly find their details.

    You do not need to search manually through every contact if the system can directly locate the contact using a key. The key may be the contact name, phone number, or email address.

    Hash Table as Contact List

    A contact list stores a person's name as a key and phone number as a value. If you search by name, you can quickly find the phone number.

    Real-World Concept Hash Table Concept Example
    Contact Name Key Rahul
    Phone Number Value 9876543210
    Search Contact Lookup by Key Find Rahul's phone number
    Update Number Update Value Change Rahul's phone number

    Key-Value Pair

    The most important idea in a hash table is the key-value pair. A key-value pair means one unique key is connected with one value.

    KEY-VALUE PAIR
    Key points to Value

    Example:

    
    "rollNumber101" -> "Rahul"
    "rollNumber102" -> "Ayesha"
    "rollNumber103" -> "John"
    

    Here, roll numbers are keys, and student names are values.

    Key Value
    101 Rahul
    102 Ayesha
    103 John
    104 Priya

    What is a Key?

    A key is a unique identifier used to find a value in a hash table. Each key should be unique because the key is used as the address or identity of a value.

    Examples of keys:

    • Student roll number
    • Employee ID
    • Product code
    • Email address
    • Username
    • Mobile number
    • Order ID
    Beginner Tip: Choose a key that uniquely identifies the data. For example, roll number is better than student name because two students may have the same name.

    What is a Value?

    A value is the data stored against a key. The value can be simple or complex. It may be a number, string, object, list, or another structure depending on the programming language.

    Examples:

    
    // Simple value
    101 -> "Rahul"
    
    // Complex value
    101 -> { name: "Rahul", course: "Programming", marks: 85 }
    

    In real projects, values are often objects or records containing multiple details.

    What is Hashing?

    Hashing is the process of converting a key into a number or index using a special function called a hash function. This index helps the hash table decide where to store the value internally.

    The user usually does not need to manage hashing manually when using built-in dictionaries or maps. However, understanding the concept helps explain why hash tables can be fast.

    HASHING IDEA
    Key goes into Hash Function produces Index
    
    // Conceptual hashing
    
    key = "S101"
    
    hashFunction(key) gives index 5
    
    Store value at index 5
    

    This process allows the program to find data quickly using the key.

    Hash Function

    A hash function is a function that takes a key and calculates a hash value or index. A good hash function should distribute keys evenly so that data does not collect in only a few positions.

    Example concept:

    
    hashIndex = hashFunction(key)
    

    The calculated hash index helps the hash table decide where the key-value pair should be stored.

    Important: In most beginner programming tasks, you use built-in dictionary or map features. The language internally handles hash functions and storage details.

    Collision in Hash Table

    A collision occurs when two different keys produce the same hash index. Since multiple keys may sometimes map to the same position, the hash table needs a way to handle this.

    Example:

    
    hashFunction("S101") -> index 5
    hashFunction("S202") -> index 5
    

    Here, both keys produce the same index. This is called a collision.

    Collision Handling

    Collision handling means managing the situation when two keys produce the same index. There are different techniques for collision handling.

    Technique Simple Meaning Basic Idea
    Chaining Store multiple values at the same index using a list. Each index can hold a linked list or collection.
    Open Addressing Find another empty position. If one place is full, search for another place.
    Linear Probing Check the next available position one by one. Move forward until empty space is found.
    Beginner Note: Collision handling is an internal topic. At beginner level, focus first on key-value storage and fast lookup.

    Common Operations on Hash Table / Dictionary

    Hash tables support several common operations. These operations are used to add, access, update, delete, and check key-value pairs.

    Operation Meaning Example
    Insert Add a new key-value pair. 101 -> Rahul
    Access / Lookup Get value using key. Find value for key 101
    Update Change value of an existing key. Update marks of roll number 101
    Delete Remove a key-value pair. Delete record with key 101
    Search Key Check whether a key exists. Does roll number 101 exist?
    Traversal Visit all key-value pairs. Display all student records.

    Inserting Data

    Inserting means adding a new key-value pair into the hash table or dictionary.

    
    // Conceptual insert operation
    
    dictionary[101] = "Rahul"
    dictionary[102] = "Ayesha"
    dictionary[103] = "John"
    

    Here, 101, 102, and 103 are keys. Rahul, Ayesha, and John are values.

    Accessing Data

    Accessing means retrieving a value using its key. This is one of the biggest strengths of a hash table.

    
    // Conceptual access operation
    
    studentName = dictionary[101]
    
    print studentName
    

    If the key 101 exists, the value Rahul is returned.

    Main Advantage Hash tables are commonly used because value lookup by key is very fast in average cases.

    Updating Data

    Updating means changing the value stored for an existing key.

    
    // Conceptual update operation
    
    dictionary[101] = "Rahul Sharma"
    

    If key 101 already exists, the old value is replaced with the new value.

    Deleting Data

    Deleting means removing a key-value pair from the hash table.

    
    // Conceptual delete operation
    
    delete dictionary[101]
    

    After deletion, key 101 and its value are no longer available in the dictionary.

    Checking if Key Exists

    Before accessing or deleting a value, it is often useful to check whether the key exists.

    
    // Conceptual key check
    
    if key 101 exists in dictionary:
        print dictionary[101]
    else:
        print "Student not found"
    

    This helps avoid errors when a key is missing.

    Java Example: HashMap

    In Java, HashMap is commonly used to store key-value pairs.

    Prerequisites: To understand this example, you should know Java classes, objects, generics basics, strings, integers, and basic collection usage.
    
    import java.util.HashMap;
    
    public class Main {
        public static void main(String[] args) {
    
            HashMap<Integer, String> students = new HashMap<>();
    
            students.put(101, "Rahul");
            students.put(102, "Ayesha");
            students.put(103, "John");
    
            System.out.println("Student with roll number 101: " + students.get(101));
    
            students.put(101, "Rahul Sharma");
    
            System.out.println("Updated student: " + students.get(101));
    
            students.remove(103);
    
            if (students.containsKey(102)) {
                System.out.println("Roll number 102 exists.");
            }
    
            System.out.println(students);
        }
    }
    

    In this example, roll numbers are keys and student names are values. The get() method retrieves a value using a key.

    JavaScript Example: Object as Dictionary

    In JavaScript, objects can be used like dictionaries for key-value storage.

    Prerequisites: To understand this example, you should know JavaScript objects, properties, strings, and console output.
    
    const students = {};
    
    students[101] = "Rahul";
    students[102] = "Ayesha";
    students[103] = "John";
    
    console.log("Student with roll number 101: " + students[101]);
    
    students[101] = "Rahul Sharma";
    
    console.log("Updated student: " + students[101]);
    
    delete students[103];
    
    if (students[102] !== undefined) {
        console.log("Roll number 102 exists.");
    }
    
    console.log(students);
    

    In this example, the object stores student names using roll numbers as keys.

    JavaScript Example: Map

    JavaScript also provides a built-in Map, which is designed for key-value storage.

    
    const students = new Map();
    
    students.set(101, "Rahul");
    students.set(102, "Ayesha");
    students.set(103, "John");
    
    console.log(students.get(101));
    
    students.set(101, "Rahul Sharma");
    
    console.log(students.get(101));
    
    students.delete(103);
    
    console.log(students.has(102));
    

    Map provides methods such as set(), get(), delete(), and has().

    PHP Example: Associative Array

    In PHP, associative arrays are commonly used as dictionaries.

    Prerequisites: To understand this example, you should know PHP arrays, echo statement, keys, values, and basic syntax.
    
    <?php
    
    $students = [];
    
    $students[101] = "Rahul";
    $students[102] = "Ayesha";
    $students[103] = "John";
    
    echo "Student with roll number 101: " . $students[101] . "<br>";
    
    $students[101] = "Rahul Sharma";
    
    echo "Updated student: " . $students[101] . "<br>";
    
    unset($students[103]);
    
    if (isset($students[102])) {
        echo "Roll number 102 exists.";
    }
    
    ?>
    

    PHP associative arrays allow values to be accessed using keys.

    C# Example: Dictionary

    In C#, Dictionary is used to store key-value pairs.

    Prerequisites: To understand this example, you should know C# classes, generic collections, strings, integers, and console output.
    
    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main()
        {
            Dictionary<int, string> students = new Dictionary<int, string>();
    
            students.Add(101, "Rahul");
            students.Add(102, "Ayesha");
            students.Add(103, "John");
    
            Console.WriteLine("Student with roll number 101: " + students[101]);
    
            students[101] = "Rahul Sharma";
    
            Console.WriteLine("Updated student: " + students[101]);
    
            students.Remove(103);
    
            if (students.ContainsKey(102))
            {
                Console.WriteLine("Roll number 102 exists.");
            }
        }
    }
    

    In this example, Dictionary stores student names using roll numbers as keys.

    Real-World Example: Student Records

    A hash table can be used to store student records using roll numbers as keys. This makes it easy to find a student quickly.

    
    students[101] = {
        name: "Rahul",
        course: "Programming Fundamentals",
        marks: 85
    }
    
    students[102] = {
        name: "Ayesha",
        course: "Programming Fundamentals",
        marks: 92
    }
    

    If we want to find the student with roll number 102, we can directly use key 102.

    Roll Number Key Student Record Value
    101 Rahul, Programming Fundamentals, 85
    102 Ayesha, Programming Fundamentals, 92
    103 John, Programming Fundamentals, 76

    Real-World Example: Product Inventory

    In an e-commerce system, product codes can be used as keys, and product details can be stored as values.

    
    products["P101"] = "Keyboard"
    products["P102"] = "Mouse"
    products["P103"] = "Monitor"
    

    If a customer searches for product code P102, the system can quickly find Mouse.

    Real-World Example: Login System

    In a login system, usernames or emails can be used as keys. User profile data can be stored as values.

    
    users["rahul@example.com"] = {
        name: "Rahul",
        role: "Student"
    }
    

    This makes it easy to find user details using email address.

    Common Applications of Hash Table / Dictionary

    Application How Hash Table is Used
    Student Management System Find student by roll number quickly.
    Employee System Find employee details by employee ID.
    Contact List Find phone number by contact name.
    E-Commerce Inventory Find product details by product code.
    Login System Find user profile by username or email.
    Counting Frequency Count how many times each word appears.
    Caching Store frequently used results for faster access.
    Database Indexing Concept Fast lookup ideas are related to indexing concepts.

    Frequency Counting Example

    Hash tables are very useful for counting frequency. For example, if we want to count how many times each word appears in a sentence, we can use a dictionary.

    
    // Conceptual frequency counting
    
    words = ["apple", "banana", "apple", "orange", "banana", "apple"]
    
    frequency["apple"] = 3
    frequency["banana"] = 2
    frequency["orange"] = 1
    

    Here, each word is a key, and its count is the value.

    Time Efficiency

    Hash tables are popular because they provide fast average-case operations for insert, search, update, and delete.

    In average cases, hash table operations are often considered very fast because the key helps locate the value directly. However, performance can become worse if too many collisions occur.

    Operation Average Case Idea Explanation
    Insert Fast Key is hashed and value is stored.
    Search Fast Key is used to find value quickly.
    Update Fast Existing key's value can be replaced.
    Delete Fast Key is used to remove the pair.
    Important: Hash tables are excellent for fast lookup, but they are not designed for maintaining sorted order by default.

    Array vs Hash Table

    Arrays and hash tables both store collections of data, but they are used differently. Arrays access data by index, while hash tables access data by key.

    Basis Array Hash Table / Dictionary
    Access Method Access using index. Access using key.
    Example marks[0] students[101]
    Best For Ordered list of values. Fast lookup by unique key.
    Key Type Index is usually numeric. Key can be number, string, or other supported type.
    Searching May require checking elements one by one. Usually faster using key lookup.
    Order Order is important and index-based. Order may not be the main purpose.

    Hash Table vs Set

    A hash table stores key-value pairs, while a set stores unique values only. Both can use hashing internally, but their purpose is different.

    Basis Hash Table / Dictionary Set
    Stores Key-value pairs. Unique values only.
    Example 101 -> Rahul 101, 102, 103
    Use Case Find value using key. Check whether a value exists.
    Duplicate Handling Keys are unique. Values are unique.

    When Should You Use Hash Table / Dictionary?

    Hash tables are useful when data needs to be found quickly using a unique key.

    Use Hash Table When

    • You need fast lookup using a key.
    • You need to store key-value pairs.
    • You need to count frequency of items.
    • You need to check whether a key exists.
    • You need to map IDs to records.
    • You need to store configuration values.
    • You need to avoid duplicate keys.
    • You need a simple in-memory lookup table.

    Advantages of Hash Table / Dictionary

    Hash tables are powerful and widely used because they make lookup operations fast and convenient.

    Benefits

    • Fast average-case lookup.
    • Fast average-case insertion.
    • Fast average-case deletion.
    • Easy key-value storage.
    • Useful for mapping IDs to records.
    • Useful for frequency counting.
    • Reduces need for repeated searching loops.
    • Makes code cleaner and more readable.
    • Available in many programming languages.
    • Useful in real-world applications and algorithms.

    Limitations of Hash Table / Dictionary

    Hash tables are useful, but they are not perfect for every situation.

    No Natural Sorted Order Hash tables are usually not designed to keep data sorted automatically.
    Collision Handling Needed Different keys may produce the same hash index, so collision handling is required internally.
    Extra Memory Usage Hash tables may use extra memory to maintain fast access.
    Key Must Be Chosen Carefully Poor key selection can cause confusion or overwrite values.
    Not Ideal for Range Queries If you need sorted range-based searching, other structures may be better.

    Common Mistakes Beginners Make

    Beginners often misunderstand hash tables because they look simple but have important rules about keys, values, and lookup behavior.

    Common Mistakes

    • Using non-unique keys accidentally.
    • Thinking hash table always stores data in sorted order.
    • Trying to access values without checking if key exists.
    • Confusing array index with dictionary key.
    • Using student name as key when names may repeat.
    • Overwriting old value by using the same key again.
    • Not understanding key-value pair structure.
    • Using hash table when ordered data is required.

    Better Approach

    • Use unique keys such as ID, roll number, or email.
    • Check whether a key exists before accessing it.
    • Use arrays when index-based order is important.
    • Use hash tables when key-based lookup is important.
    • Remember that keys should identify values clearly.
    • Use meaningful key names and value structures.
    • Do not assume automatic sorting.
    • Practice insert, get, update, and delete operations.

    Best Practices for Hash Tables

    Good use of hash tables depends on choosing proper keys and keeping data organized.

    Recommended Practices

    • Choose keys that are unique.
    • Use meaningful keys such as roll number, ID, or email.
    • Check if key exists before accessing sensitive data.
    • Use values that match the problem requirement.
    • Use objects as values when multiple details are needed.
    • Do not use hash tables when sorted order is the main requirement.
    • Use hash tables for fast lookup and frequency counting.
    • Keep key naming consistent.
    • Avoid duplicate keys unless updating is intended.
    • Understand basic collision concept even when using built-in dictionaries.

    Mini Practice Activity

    Complete the following practice tasks to strengthen your understanding of hash tables and dictionaries.

    Task Description Expected Learning
    Task 1 Create a dictionary of student roll numbers and names. Understand key-value pairs.
    Task 2 Find a student name using roll number. Practice lookup by key.
    Task 3 Update the name of one student. Practice value update.
    Task 4 Delete one student record using roll number. Practice delete operation.
    Task 5 Check whether a roll number exists before accessing it. Practice safe key checking.
    Task 6 Count frequency of words in a sentence using dictionary. Understand frequency counting use case.

    Frequently Asked Questions

    1. What is a hash table?

    A hash table is a data structure that stores data in key-value pairs and allows fast access to values using keys.

    2. What is a dictionary in programming?

    A dictionary is a key-value data structure. It is another common name for a hash table or map in many programming languages.

    3. What is a key-value pair?

    A key-value pair means one unique key is connected with one value. The key is used to find the value.

    4. What is hashing?

    Hashing is the process of converting a key into a hash value or index using a hash function.

    5. What is a hash function?

    A hash function is a function that takes a key and calculates an index or hash value for storage and lookup.

    6. What is collision?

    A collision occurs when two different keys produce the same hash index.

    7. Are dictionary keys unique?

    Yes. In most dictionary or hash table structures, keys are unique. If the same key is used again, the old value may be replaced.

    8. Can values be duplicated?

    Yes. Different keys can have the same value, but keys should be unique.

    9. When should I use a hash table?

    Use a hash table when you need fast lookup using a key, such as finding student details by roll number or product details by product code.

    10. What is the main advantage of a hash table?

    The main advantage is fast average-case lookup, insertion, update, and deletion using keys.

    Summary

    A hash table or dictionary is a data structure that stores data as key-value pairs. It is useful when we need to quickly find a value using a unique key.

    Hash tables are commonly used for student records, employee systems, product inventories, contact lists, login systems, caching, and frequency counting. They are available in many programming languages under names such as HashMap, Dictionary, Map, object, or associative array.

    The main idea behind hash tables is hashing. A hash function converts a key into an index so data can be stored and accessed quickly. Sometimes collisions happen, and the hash table handles them internally using collision-handling techniques.

    Key Takeaway

    A hash table or dictionary stores data using key-value pairs. It is best when you need fast lookup, insertion, update, and deletion using a unique key such as roll number, employee ID, product code, username, or email.