0% found this document useful (0 votes)
14 views

Introduction to Dictionaries

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Introduction to Dictionaries

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Introduction to Dictionaries in Data Structures

A dictionary, also known as a hash table or associative array, is a data


structure that stores data in key-value pairs. It allows for efficient retrieval,
insertion, and deletion of values based on unique keys.

key-value pair is a fundamental concept used to represent a relationship


between two pieces of data. In this pair, the key acts as a unique identifier,
while the value holds the actual data associated with that key. This structure
is widely used in associative data structures like dictionaries, hash tables,
and maps.

Key-Value Pair Structure

 Key: The key is a unique identifier, meaning it should be distinct within a


particular collection to avoid ambiguity. It's used to quickly locate the
corresponding value.
 Value: The value is the data or information that is associated with the key.
Unlike keys, values don’t have to be unique.

Representation

In different programming languages and data structures, key-value pairs can be represented in
various ways:

1.

Python Dictionary: In Python, a dictionary stores data as key-value pairs.

data = {"name": "Alice", "age": 30, "city": "New York"}

# "name", "age", and "city" are keys, while "Alice", 30, and "New York" are their values.

2. Hash Table: In a hash table, keys are mapped to values using a


hash function that generates an index based on the key.

Key | Hash | Index | Value

-------|---------|-------|-------
"name" | 214 |5 | "Alice"

"age" | 123 |8 | 30

"city" | 332 |2 | "New York"

3. JavaScript Object: In JavaScript, objects use key-value pairs.

const data = { name: "Alice", age: 30, city: "New York" };

Visual Representation

"name": "Alice",

"age": 30,

"city": "New York"

Key Features

1. Key-Value Pair:

Each entry in a dictionary consists of a key and its corresponding


value. The key acts as an identifier, while the value is the data associated
with that key.

2. Uniqueness of Keys:

Keys in a dictionary are unique; no two entries can have the same key.
This uniqueness allows for efficient access to values.
3. Fast Lookup:

Dictionaries provide average-case constant time complexity \(O(1)\)


for lookup operations, thanks to the underlying hash table mechanism. This
efficiency makes them suitable for scenarios where quick data retrieval is
crucial.

4. Dynamic Size:

Unlike arrays, dictionaries can grow and shrink dynamically as


elements are added or removed. This flexibility is beneficial for applications
where the number of items can change frequently.

Operations

1. Insertion: Adding a new key-value pair to the dictionary.

- Example: `dict["key"] = value`

2. Deletion: Removing a key-value pair based on the key.

- Example: `del dict["key"]`

3. Lookup: Retrieving the value associated with a given key.

- Example: `value = dict["key"]`

4. Updating: Changing the value associated with an existing key.

- Example: `dict["key"] = new_value`


5. Iteration: Dictionaries can be iterated over to access keys, values, or
both.

Example

Here's a simple example of a dictionary in Python:

---python

# Creating a dictionary

student_grades = {

"Alice": 85,

"Bob": 90,

"Charlie": 78

# Inserting a new entry

student_grades["David"] = 92

# Updating an entry

student_grades["Alice"] = 88

# Looking up a value

print(student_grades["Bob"]) # Output: 90
# Deleting an entry

del student_grades["Charlie"]

# Iterating over the dictionary

for student, grade in student_grades.items():

print(f"{student}: {grade}")

In computer science, a dictionary is an abstract data type that represents an ordered


or unordered list of key-value pair elements where keys are used to search/locate the
elements in the list. In a dictionary ADT, the data to be stored is divided into two parts:

 Key
 Value.
Each item stored in a dictionary is represented by a key-value pair. Key is used to
access the elements in the dictionary. With the key we can access value which has
more information about the element.

Characteristics of Dictionary
 Key-Value Pairs: Dictionaries store data as key-value pairs where each key is unique
and maps to exactly one value.
 Direct Access: The primary feature of dictionaries is to provide fast access to elements
not by their position, as in lists or arrays, but by their keys.
 Dynamic Size: Like many abstract data types, dictionaries typically allow for dynamic
resizing. New key-value pairs can be added, and existing ones can be removed.
 Ordering: Some dictionaries maintain the order of elements, such as ordered maps or
sorted dictionaries. Others, like hash tables, do not maintain any particular order.
 Key Uniqueness: Each key in a dictionary must be unique, though different keys can
map to the same value.

Fundamental Operations of Dictionary


 Insert: Add a new key-value pair to the dictionary.
 Search: Retrieve the value associated with a particular key.
 Delete: Remove a key-value pair from the dictionary.
 Update: Change the value associated with a given key.
 Keys: Return a collection of all the keys in the dictionary.
 Values: Return a collection of all the values in the dictionary.

Types of Dictionary
There are two major variations of dictionaries:

Ordered dictionary.

 In an ordered dictionary, the relative order is determined by comparison on keys.


 The order should be completely dependent on the key.

Unordered dictionary.

 In an unordered dictionary, no order relation is assumed on keys.


 Only equality operation can be performed on the keys.

Implementation of Dictionary
A dictionary can be implemented in several ways, such as

 Fixed length array.


 Linked lists.
 Hashing
 Trees (BST, Balancing BSTs, Splay trees, Tries etc.)

Linear list representation


A linear list representation of a dictionary involves using a simple list structure (like an
array or a linked list) to store key-value pairs. Each entry in the list consists of two parts:
a unique key and an associated value. Let's walk through the implementation step by
step:
Step 1: Initialization
When you initialize the dictionary, you start with an empty list. This list will hold all the
key-value pairs.

dictionary = []

Step 2: Insertion
To insert a new key-value pair into the dictionary:
Check for the Key's Existence: Iterate through the list to check if the given key
already exists.
Update or Insert:

 If the key exists, update the associated value.


 If the key does not exist, append a new key-value pair to the list.

function insert(key, value):


for each pair in dictionary:
if pair.key == key:
pair.value = value
return
dictionary.append((key, value))

Step 3: Search
To find a value associated with a given key:

 Iterate Through the List: Go through each key-value pair in the list.
 Compare Keys: Check if the current key matches the search key.
 Return Value if Found: If a match is found, return the associated value.

function search(key):
for each pair in dictionary:
if pair.key == key:
return pair.value
return None // Or indicate that the key was not found
Step 4: Deletion
To delete a key-value pair from the dictionary:

 Search for the Key: Iterate through the list to find the key.
 Remove the Pair: Once the key is found, remove the key-value pair from the list.

function delete(key):
for each pair in dictionary:
if pair.key == key:
remove pair from dictionary
return

Step 5: Traversal
To traverse the dictionary and access each key-value pair:

 Iterate Through the List: Go through each key-value pair in the list.
 Process Each Pair: Perform the desired operation (like printing) on each pair.

function traverse():
for each pair in dictionary:
process(pair.key, pair.value)

Step 6: Update
Updating a value for a specific key follows the same procedure as insertion. If the key
exists, its value is updated; otherwise, the key-value pair is added.

Advantages linear list representation of a dictionary

 Simplicity: A linear list is simple and easy to implement.


 Dynamic Size: The list can grow or shrink as key-value pairs are added or removed.

Disadvantages linear list representation of a dictionary

 Search Time: The search time is linear in the worst case, which can be inefficient for
large numbers of entries.
 Insertion Time: Similar to search, if the list is being kept in sorted order, then finding the
correct place to insert a new key can take linear time.
 Deletion Time: Removing an entry requires a search followed by a deletion, both of
which can be inefficient in a large list.
Skip list representation
A Skip List is an advanced data structure that allows for fast search within an ordered sequence
of elements, providing a clever alternative to balanced trees. It is effectively a linked-list that
adds multiple layers on top of the standard list to enable faster search times.
Here's how a Skip List is typically represented:

 Base Layer:
 The bottom layer is a standard linear linked list that contains all the elements in
the set, sorted by key.
 Express Layers:
 Above the base layer are one or more layers of "express lanes." Each layer is a
linked list that skips over some elements from the list below it. The topmost layer
has the fewest elements, and each layer doubles (or varies by some factor) the
number of elements it skips compared to the layer directly beneath it.
A Skip List is an efficient, probabilistic data structure that enables fast search, insertion, and
deletion operations, akin to balanced trees like AVL or Red-Black trees. Here's a step-by-step
explanation of how a Skip List is used to represent a dictionary:

Step 1: Understanding the Structure


A Skip List is composed of several layers of linked lists, where each higher layer provides a
"shortcut" through the lower layers. The bottom layer (Layer 0) contains all the elements, and
each successive layer contains a subset of these elements, chosen randomly.

Step 2: Layered Links


Each node in the Skip List contains pointers to the next node in the same layer and down to the
same node in the layer immediately below it.

Step 3: Initialization
When initializing a Skip List:

 Create a "head" node with pointers set to NULL for each layer.
 Set a maximum level for the list, which determines how many layers the list can have.
 Optionally, set a "tail" node with maximum possible key value to mark the end of each
level.

Step 4: Insertion
To insert a key-value pair:

 Find the Position: Start from the topmost layer and move forward until you find a node
with a greater key or reach the end of the layer. Then, move down one layer and continue.
Record the nodes where you move down a level.
 Choose a Random Level: For the new node, randomly decide the number of layers
(level) it will participate in (usually done with a coin flip algorithm).
 Rearrange Pointers: For each level up to the chosen level, update the pointers of the
recorded nodes to include the new node.

Step 5: Search
To search for a key:

 Start from the topmost layer of the head node.


 Move forward in the current layer until you find a node with a greater key or reach the
end.
 If you find a greater key, move down one layer.
 Repeat until you reach the bottom layer. If the key matches, return the value; otherwise,
the key is not in the list.

Step 6: Deletion
To delete a key-value pair:

 Perform a search for the key, keeping track of the predecessors at each level.
 If the key is found, update the pointers of these predecessor nodes to skip the node being
deleted.
 Remove the node and deallocate its memory.

Step 7: Random Level Generation


The level for a new node is typically determined using a random process. A common method is
a coin flip algorithm: a random level is generated, and as long as a coin flip results in heads (or a
random value meets a certain condition), you increase the level.

Step 8: Traversal
To traverse the Skip List, simply follow the bottom layer from the head node to the end,
processing or printing the values.

Algorithm for Implementing Skip List

Algorithm 1: Randomly Selecting a New Node's Level


Data: p- the probability to advance a node from one level to the next, max Level - the maximal
allowed level, ∞ if unrestricted.
Result: the randomly selected level of a new node.
Function RANDOM-LEVEL (p, maxLevel) :
Level ← 1
// RANDOM draws a random number from the uniform distribution over [0,1]
while (RANDOM() ≤ p) and (level < maxLevel) do
level ← level + 1
end
return level
end

Algorithm 2: Inserting a Value Into a Skip List


Data: list the skip list, v- the value to insert, maxLevel - the maximal level of a new node
Result: v is inserted into the list
function INSERT ( head, v, maxLevel):
level←RANDOM-LEVEL (maxLevel)
if level > list.max Level then
for klist.max Level, list.max Level 1,..., level do
list.heads[k] ← make an empty node (NULL)
end
list.max Level ← level
end
update ← make an empty array with level reserved elements
y← make a node whose value is v
for k←list.max Level, list.maxLevel – 1,...,1 do
x←list.heads[k]
if x is empty then
list.heads[k] ← y
else
z← x.successors[k]
while (z ≠ NULL) and (v > z.value) do
x ← z
z← z.pointers[k]
end
x.successors[k] ← y
y.successors[k] ← z
end
end
end

Algorithm 3: Searching a Skip List


Data: list - the skip list to search, v - the value to find
Result: x- the node containing v, or failure if v isn't in the list.
function SEARCH ( list, v):
x←list.heads [list.max Level]
for k←list.max Level, list.max Level - 1,..., 1 do
if x = NULL then
x←list.heads[k]
end
while (x.successors[k] ≠ NULL) and (x.successors[k].value < v) do
x←x.successors[k]
end
end
// At this point: x.value < v ≤ x.successors[1].value
If x.successors [1] ≠ NULL and x.successors[1].value = v then
return x.successors [1]
else
return failure
end
end

Algorithm 4: Deleting a Value From a Skip List


Data: list the skip list, v - the value to delete
Result: if present, a node whose value is v is deleted from list.
function :
update← make an empty array with list.max Level NULL elements
for k←list.max Level, list.max Level 1,..., 1 do
x←list.heads[k]
y ← x.successors[k]
while (y ≠ NULL) and (v > y.value) do
x← y
y←x.successors[k
end
if y ≠ NULL then
// At this point we have that y.value> v
if (y.value = v) then
// y will be deleted, and we'll point x to
y's k-th successor
update[k] ← x
end
end
end
if y.value = v then
// v is in the list, so we delete y by removing any links to it
for k ←1,2,..., list.max Level do
if update[k] ≠ NULL then
update[k].successors[k] ← y.successors[k]
end
end
// We decrease the max level if it's been completely deleted
while (list.maxLevel > 1) and (list.heads [list.max Level] = NULL) do
list.max Level ← list.max Level - 1
end
end
end

You might also like