Dictionary in Data Structure
Dictionary in Data Structure
A complete beginner-friendly guide to understanding Dictionary, Key-Value Pairs, Hashing, Operations, Time Complexity, and Real-World Applications.
Introduction
In data structures, a Dictionary is an important abstract data type used to store data in the form of key-value pairs. Instead of accessing data using a numeric index like an array, a dictionary allows us to access data using a meaningful key.
A dictionary is also known by different names in different programming languages. In some languages it is called a Map, in some it is called a HashMap, and in some it is called an Associative Array. Although the names may be different, the core concept remains the same: store a value and retrieve it using a unique key.
Real-Life Example of Dictionary
Phone Directory Example
Imagine a phone directory where a person's name is used to find their phone number. Here, the name works as the key, and the phone number works as the value.
| Key | Value |
|---|---|
| Rumman | 9876543210 |
| Amit | 9123456780 |
| Priya | 9988776655 |
If we want Amit's phone number, we do not need to check every number one by one. We simply search using the key "Amit" and get the value 9123456780.
Definition of Dictionary
Each key in a dictionary must be unique. A single key points to one specific value. However, different keys may have the same value depending on the situation.
Example
{
"student_id": 101,
"name": "Rumman Ansari",
"course": "Data Structures",
"city": "Kolkata"
}
In the above example, student_id, name, course, and city are keys. Their corresponding data such as 101, Rumman Ansari, Data Structures, and Kolkata are values.
Prerequisites to Understand Dictionary
Before learning Dictionary in data structure, students should have a basic understanding of the following topics:
Required Knowledge
- Variables: To understand how data is stored in memory.
- Arrays: To compare index-based access with key-based access.
- Functions: To understand operations like insert, search, update, and delete.
- Basic Programming Logic: To understand how data is processed.
- Hashing Concept: Helpful for understanding the internal working of dictionaries.
Why Do We Need Dictionary?
Suppose we have a list of students and their marks. If we store the data in an array, we may need to search through the entire array to find the marks of a particular student. This can be slow when the data size is large.
A dictionary solves this problem by allowing direct access using a key. If the student's name or roll number is used as the key, the marks can be found quickly.
Without Dictionary
- Need to search one by one
- Slow for large data
- Difficult to manage key-value relationships
- Code becomes less readable
With Dictionary
- Access data directly using key
- Fast lookup operation
- Easy to represent real-world relationships
- Code becomes clean and meaningful
Structure of Dictionary
A dictionary is made up of multiple entries. Each entry contains two parts:
Key
A key is a unique identifier used to access a value.
Example keys can be roll number, employee ID, username, product code, or email ID.
Value
A value is the actual data stored against a key.
Example values can be student details, salary information, profile data, product price, or marks.
Characteristics of Dictionary
Important Features
- Key-Value Pair: Dictionary stores data as a relationship between a key and a value.
- Unique Keys: Every key must be unique inside the dictionary.
- Fast Access: Values can be accessed quickly using keys.
- Dynamic Size: A dictionary can grow or shrink during program execution.
- Flexible Values: Values can be numbers, strings, objects, arrays, or another dictionary.
- No Duplicate Keys: If a duplicate key is added, the old value is usually updated.
- Efficient Searching: Dictionaries are commonly used when fast searching is required.
Basic Operations on Dictionary
A dictionary supports several important operations. These operations make dictionary useful in many practical programming problems.
Insert Operation
Insert operation adds a new key-value pair into the dictionary.
If the key does not already exist, a new entry is created. If the key already exists, the value may be updated depending on the programming language.
Search / Lookup Operation
Search operation finds the value associated with a given key.
This is one of the most important operations of a dictionary because dictionaries are mainly used for fast lookup.
Update Operation
Update operation changes the value of an existing key.
For example, if a student's marks are changed, the marks can be updated using the student's roll number as the key.
Delete Operation
Delete operation removes a key-value pair from the dictionary.
Once a key is deleted, its associated value is also removed from the dictionary.
Traversal Operation
Traversal means visiting each key-value pair one by one.
Traversal is useful when we want to display all data stored in a dictionary.
Dictionary Operations Summary
| Operation | Meaning | Example |
|---|---|---|
| Insert | Add a new key-value pair | 101 → "Rumman" |
| Search | Find value using key | Find student name using roll number 101 |
| Update | Change value of existing key | Update marks of roll number 101 |
| Delete | Remove key-value pair | Delete record of roll number 101 |
| Traversal | Visit all key-value pairs | Display all student records |
Dictionary Example Using JavaScript
In JavaScript, a dictionary-like structure can be created using an object or the Map data structure. The following example shows basic dictionary operations using a JavaScript object.
// Creating a dictionary using JavaScript object
let student = {
rollNo: 101,
name: "Rumman Ansari",
course: "Data Structures"
};
// Access value using key
console.log(student.name);
// Insert new key-value pair
student.city = "Kolkata";
// Update existing value
student.course = "DSA";
// Delete key-value pair
delete student.rollNo;
// Display final dictionary
console.log(student);
Output
Rumman Ansari
{
name: "Rumman Ansari",
course: "DSA",
city: "Kolkata"
}
Dictionary Example Using Java HashMap
In Java, dictionary functionality is commonly implemented using HashMap. HashMap stores data in key-value pairs and provides fast access using keys.
import java.util.HashMap;
public class DictionaryExample {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
// Insert key-value pairs
students.put(101, "Rumman");
students.put(102, "Amit");
students.put(103, "Priya");
// Search value using key
System.out.println(students.get(101));
// Update value
students.put(102, "Amit Kumar");
// Delete value
students.remove(103);
// Display dictionary
System.out.println(students);
}
}
Output
Rumman
{101=Rumman, 102=Amit Kumar}
Internal Working of Dictionary
Most dictionaries are internally implemented using a concept called Hashing. Hashing helps convert a key into an index where the value can be stored or found quickly.
A hash function takes a key as input and converts it into a numeric index. This index helps the dictionary decide where to store the value in memory.
Simple Hash Function Example
Suppose we have a key 101 and table size 10. A simple hash function can be:
Now calculate:
So, the value related to key 101 may be stored at index 1. This makes searching faster because the dictionary can directly calculate the location.
What is Collision in Dictionary?
A collision occurs when two different keys generate the same index using the hash function. Since both keys want to store values at the same location, the dictionary must handle this situation carefully.
Example of Collision
Suppose the table size is 10:
\( 111 \mod 10 = 1 \)
Both keys 101 and 111 generate index 1. This is called a collision.
Collision Handling Techniques
Common Techniques
- Chaining: Stores multiple values at the same index using a linked list or similar structure.
- Linear Probing: Searches for the next empty location in the table.
- Quadratic Probing: Uses a quadratic formula to find another empty slot.
- Double Hashing: Uses another hash function to find a new position.
Time Complexity of Dictionary
Time complexity tells us how much time an operation takes as the size of data increases. Dictionary operations are usually very fast because of hashing.
| Operation | Average Case | Worst Case | Explanation |
|---|---|---|---|
| Search | O(1) | O(n) | Usually direct access using hash index, but collision may increase time. |
| Insert | O(1) | O(n) | Usually inserted directly, but collision handling may take extra time. |
| Delete | O(1) | O(n) | Usually removed quickly using key, but collision cases may take more time. |
| Traversal | O(n) | O(n) | Every key-value pair must be visited once. |
Space Complexity of Dictionary
Space complexity of a dictionary is generally O(n), where n is the number of key-value pairs. This is because memory is required to store every key and its associated value.
Sometimes dictionaries may require extra memory to maintain internal hash tables, empty slots, or linked structures for collision handling.
Dictionary vs Array
Arrays and dictionaries are both used to store data, but they are used in different situations. Arrays are index-based, while dictionaries are key-based.
| Basis | Array | Dictionary |
|---|---|---|
| Access Method | Accessed using numeric index | Accessed using key |
| Data Format | Stores values in sequence | Stores data as key-value pairs |
| Example | marks[0] | marks["Rumman"] |
| Searching | May require linear search | Usually fast using key |
| Best Use | When order and position matter | When fast lookup by key is needed |
| Readability | Less meaningful for named data | More meaningful because keys describe data |
Types of Dictionary
Based on internal implementation and ordering behavior, dictionaries can be classified into different types.
Unordered Dictionary
Does not maintain keys in sorted order.
In an unordered dictionary, data is stored based on hashing. The main focus is fast access, not maintaining order. HashMap is a common example of an unordered dictionary.
Ordered Dictionary
Maintains insertion order or sorted order depending on implementation.
Ordered dictionaries are useful when the order of elements is important, such as maintaining the sequence in which records were inserted.
Tree-Based Dictionary
Uses tree structures like Binary Search Tree, AVL Tree, or Red-Black Tree.
Tree-based dictionaries are useful when keys need to be stored in sorted order. Their common operations usually take O(log n) time.
Dictionary Implementation Methods
| Implementation | Description | Common Time Complexity |
|---|---|---|
| Array-Based Dictionary | Stores key-value pairs in an array and searches linearly. | O(n) |
| Linked List-Based Dictionary | Stores each key-value pair as a node in a linked list. | O(n) |
| Hash Table-Based Dictionary | Uses hash function to calculate index for fast access. | O(1) average |
| Tree-Based Dictionary | Stores keys in sorted tree structure. | O(log n) |
Advantages of Dictionary
Benefits
- Fast Searching: Values can be retrieved quickly using keys.
- Easy Data Representation: Real-world relationships can be represented naturally.
- Readable Code: Keys make the meaning of data clear.
- Dynamic Structure: New data can be added and removed easily.
- Flexible Usage: Useful in databases, APIs, caching, compilers, and many applications.
- Efficient Updates: Existing values can be updated directly using keys.
Disadvantages of Dictionary
Limitations
- Extra Memory: Hash-based dictionaries may require additional memory.
- Collision Problem: Different keys may generate the same hash index.
- No Natural Indexing: Values are not usually accessed by position like arrays.
- Worst Case Performance: In poor collision situations, operations may become slower.
- Key Restrictions: Some languages require dictionary keys to be immutable or hashable.
Applications of Dictionary
Dictionaries are widely used in programming because many real-world problems involve finding data using a unique identifier.
Student Records
- Roll number → Student details
- Fast search of marks and attendance
- Easy update of student information
Phone Directory
- Name → Phone number
- Quick lookup by contact name
- Easy insertion and deletion of contacts
E-Commerce System
- Product ID → Product details
- Fast product search
- Useful for inventory management
Database Indexing
- Primary key → Record location
- Improves searching speed
- Useful in large datasets
Caching
- URL → Cached response
- Reduces repeated computation
- Improves application performance
Compiler Symbol Table
- Variable name → Memory information
- Used during program compilation
- Helps track identifiers
Practical Example: Counting Word Frequency
One common use of dictionary is to count how many times each word appears in a sentence. In this case, the word becomes the key and its frequency becomes the value.
let sentence = "data structure data dictionary structure data";
let words = sentence.split(" ");
let frequency = {};
for (let word of words) {
if (frequency[word]) {
frequency[word] = frequency[word] + 1;
} else {
frequency[word] = 1;
}
}
console.log(frequency);
Output
{
data: 3,
structure: 2,
dictionary: 1
}
This example shows how dictionary can be used for frequency counting. This technique is very useful in text processing, search engines, data analysis, and natural language processing.
When Should We Use Dictionary?
Common Mistakes Students Make
Avoid These Mistakes
- Thinking that dictionary and array are exactly the same.
- Using duplicate keys and expecting both values to remain separately.
- Forgetting that keys must be unique.
- Assuming dictionary always stores data in sorted order.
- Ignoring collision handling in hash-based dictionaries.
- Using dictionary when a simple array is more suitable.
Interview Questions on Dictionary
What is a Dictionary in data structure?
A Dictionary is a data structure that stores data in key-value pairs. Each key is unique and is used to access its corresponding value.
Why is Dictionary faster than linear search?
Dictionary is usually implemented using hashing, which allows direct calculation of the storage location. Therefore, average search time is generally O(1), while linear search takes O(n).
Can two keys have the same value?
Yes, two different keys can have the same value. However, two identical keys cannot exist separately in the same dictionary.
What happens if we insert a duplicate key?
In most programming languages, inserting a duplicate key updates or replaces the old value with the new value.
What is collision in dictionary?
Collision happens when two different keys produce the same hash index. Collision handling techniques are used to manage such situations.
Quick Revision
| Point | Summary |
|---|---|
| Data Format | Key-value pairs |
| Key Property | Keys must be unique |
| Main Benefit | Fast lookup using key |
| Common Implementation | Hash table |
| Average Search Time | O(1) |
| Worst Search Time | O(n) |
| Common Names | Map, HashMap, Associative Array |
| Best Use Case | Fast searching and mapping relationships |
Conclusion
A Dictionary is one of the most useful and powerful data structures in computer science. It allows data to be stored in a meaningful way using key-value pairs. Instead of remembering numeric positions, programmers can use meaningful keys to access values quickly.
Dictionaries are commonly used in applications where fast lookup, insertion, deletion, and update operations are required. They are used in databases, caches, phone books, student management systems, compilers, APIs, search engines, and many other real-world systems.
Final Takeaway
A Dictionary is best understood as a key-based data storage system. If an array answers the question "What is stored at this position?", then a dictionary answers the question "What value belongs to this key?".