Nearby lessons
62 of 108Python - Dictionary Data Structure
Introduction to Dictionary
We can use List, Tuple and Set to represent a group of individual objects as a single entity.
If we want to represent a group of objects as key-value pairs, then we should use a Dictionary.
A Dictionary is one of Python's built-in collection data types.
Real-Life Examples
Some common examples of Dictionary are:
- Roll Number → Student Name
- Phone Number → Address
- IP Address → Domain Name
Characteristics of Dictionary
A Dictionary has the following characteristics:
- Data is stored as key-value pairs.
- Duplicate keys are not allowed.
- Duplicate values are allowed.
- Heterogeneous objects are allowed for both keys and values.
- Insertion order is not preserved.
- Dictionary objects are mutable.
- Dictionary objects are dynamic.
- Indexing and slicing are not applicable.
Note: In C++ and Java, a Dictionary is known as a Map, whereas in Perl and Ruby, it is known as a Hash.
Feature 1 - Dictionary Stores Data as Key-Value Pairs
Every element in a Dictionary consists of two parts:
- A Key
- A Value
Syntax
main.py
No output captured.
Feature 2 - Duplicate Keys are Not Allowed
A Dictionary cannot contain duplicate keys.
If we insert an entry with an existing key, the old value is replaced by the new value.
Example
main.py
{101: 'sunny', 102: 'ravi', 103: 'shiva'}Explanation
The key 101 already exists in the Dictionary.
Therefore, its old value "durga" is replaced with "sunny".
Feature 3 - Duplicate Values are Allowed
Unlike keys, duplicate values are allowed in a Dictionary.
Example
main.py
{101: 'durga', 102: 'durga', 103: 'shiva'}Feature 4 - Heterogeneous Keys and Values are Allowed
A Dictionary can store different types of keys and values.
Example
main.py
{100: 'Durga', 'A': 10, 10.5: 'Python', True: 'Yes'}Feature 5 - Insertion Order is Not Preserved
A Dictionary does not preserve the insertion order.
Therefore, the output order may be different from the insertion order.
Feature 6 - Dictionary is Mutable
Dictionary objects are mutable.
After creating a Dictionary, we can:
- Add new key-value pairs.
- Modify existing values.
- Remove key-value pairs.
Feature 7 - Dictionary is Dynamic
The size of a Dictionary can be increased or decreased whenever required.
Feature 8 - Indexing and Slicing are Not Supported
Dictionary elements are accessed using keys, not indexes.
Therefore:
- Indexing is not supported.
- Slicing is not supported.
Creating Dictionary Objects
There are different ways to create Dictionary objects in Python.
Method 1 - Creating an Empty Dictionary
We can create an empty Dictionary in two ways.
Syntax
main.py
No output captured.
Example
main.py
{}Adding Key-Value Pairs
After creating an empty Dictionary, we can add key-value pairs one by one.
Example
main.py
{100: 'durga', 200: 'ravi', 300: 'shiva'}Method 2 - Creating a Dictionary with Known Data
If the data is already known, we can directly create a Dictionary.
Syntax
main.py
No output captured.
Example
main.py
{100: 'durga', 200: 'ravi', 300: 'shiva'}Summary
| Topic | Description |
|---|---|
| Dictionary | Collection of key-value pairs. |
| Duplicate Keys | Not Allowed. |
| Duplicate Values | Allowed. |
| Heterogeneous Keys | Allowed. |
| Heterogeneous Values | Allowed. |
| Insertion Order | Not Preserved. |
| Mutable | Yes. |
| Dynamic | Yes. |
| Indexing | Not Supported. |
| Slicing | Not Supported. |
| Empty Dictionary | {} or dict() |
| Dictionary with Data | {key: value} |
Important Notes
- A Dictionary stores data as key-value pairs.
- Duplicate keys are not allowed.
- If a duplicate key is inserted, the old value is replaced with the new value.
- Duplicate values are allowed.
- Heterogeneous keys and values are allowed.
- Dictionary objects are mutable.
- Dictionary objects are dynamic.
- Dictionaries do not support indexing and slicing.
- An empty Dictionary can be created by using
{}ordict(). - If the data is already known, a Dictionary can be created directly by using
{key: value}syntax. - In C++ and Java, a Dictionary is called a Map.
- In Perl and Ruby, a Dictionary is called a Hash.
Accessing Dictionary Elements
Dictionary elements are accessed by using keys.
Unlike Lists and Tuples, Dictionary objects do not support indexing and slicing.
If the specified key is available, Python returns the corresponding value.
If the key is not available, Python raises a KeyError.
Syntax
main.py
No output captured.
Example 1 - Access Existing Values
main.py
Durga Shiva
Explanation
The Dictionary searches for the specified key.
If the key exists, the corresponding value is returned.
Example 2 - Access a Missing Key
main.py
KeyError: 300
KeyError
If we try to access a key that is not present in the Dictionary, Python raises a KeyError.
This error indicates that the specified key does not exist.
How to Prevent KeyError
Before accessing a value, we can check whether the key is available in the Dictionary.
In Python 3, the recommended approach is to use the in operator.
Using the in Operator
main.py
Ravi Key Not Found
Note about has_key()
In Python 2, the has_key() method was used to check whether a key exists.
This method has been removed from Python 3.
In Python 3, always use the in operator.
Adding New Key-Value Pairs
We can add a new key-value pair simply by assigning a value to a new key.
If the key does not exist, a new entry is created.
Syntax
main.py
No output captured.
Example 1 - Add New Entry
main.py
{100: 'Durga', 200: 'Ravi', 300: 'Shiva'}Explanation
Initially the Dictionary is empty.
Each assignment creates a new key-value pair.
Updating Existing Values
If the specified key already exists, assigning a new value updates the existing value.
No duplicate key is created.
Syntax
main.py
No output captured.
Example 2 - Update Existing Value
main.py
{100: 'Durga', 200: 'Sunny', 300: 'Shiva'}Explanation
The key 200 already exists.
Therefore, only its value is updated.
Example 3 - Add and Update Together
main.py
{101: 'Amit', 102: 'Karan', 103: 'Vijay'}Student Record Program
The following program stores student details in a Dictionary.
The Roll Number is used as the key and the Student Name is used as the value.
Program
main.py
{101: 'Rahul', 102: 'Amit', 103: 'Neha'}
Student with Roll No 102 = Amit
Updated Dictionary:
{101: 'Rahul', 102: 'Priya', 103: 'Neha'}Summary
| Operation | Description |
|---|---|
| Access Value | Use the key. |
| Missing Key | Raises KeyError. |
| Check Key | Use in operator. |
| Add New Entry | Assign a value to a new key. |
| Update Value | Assign a new value to an existing key. |
| Duplicate Key | Old value is replaced. |
Important Notes
- Dictionary elements are accessed using keys.
- Indexing and slicing are not supported.
- If a key is not present, Python raises
KeyError. - Use the
inoperator to check whether a key exists. - The
has_key()method is available only in Python 2. - Assigning a value to a new key creates a new entry.
- Assigning a value to an existing key updates the existing value.
- Duplicate keys are not created.
- The Dictionary size increases automatically when new entries are added.
- Dictionary objects are mutable and dynamic.
Dictionary Functions (Basic)
Python provides several built-in functions and methods to work with Dictionary objects.
In this part, we will learn the following:
dict()len()get()pop()popitem()
dict() Function
The dict() function is used to create a Dictionary object.
It creates an empty Dictionary if no argument is provided.
It can also convert suitable objects into a Dictionary.
Syntax
main.py
No output captured.
Example 1 - Create an Empty Dictionary
main.py
{}Example 2 - Create Dictionary from Key-Value Pairs
main.py
{100: 'Durga', 200: 'Ravi', 300: 'Shiva'}len() Function
The len() function returns the total number of key-value pairs available in a Dictionary.
Syntax
main.py
No output captured.
Example 1 - Count Entries
main.py
3
Example 2 - Empty Dictionary
main.py
0
get() Method
The get() method returns the value associated with the specified key.
If the key is not available, it returns None instead of raising a KeyError.
Syntax
main.py
No output captured.
Example 1 - Existing Key
main.py
Durga
Example 2 - Missing Key
main.py
None
Example 3 - Default Value
main.py
Key Not Found
Advantages of get()
- Prevents
KeyError. - Returns
Noneif the key is not available. - A custom default value can also be returned.
pop() Method
The pop() method removes the specified key from the Dictionary.
It also returns the corresponding value.
If the key is not available, Python raises a KeyError.
Syntax
main.py
No output captured.
Example 1 - Remove Existing Key
main.py
Ravi
{100: 'Durga', 300: 'Shiva'}Example 2 - Remove Missing Key
main.py
KeyError: 200
Important Notes - pop()
- Removes the specified key-value pair.
- Returns the removed value.
- Raises
KeyErrorif the key is not available.
popitem() Method
The popitem() method removes and returns one key-value pair from the Dictionary.
The returned value is in the form of a tuple.
Syntax
main.py
No output captured.
Example
main.py
(300, 'Shiva')
{100: 'Durga', 200: 'Ravi'}Explanation
The removed item is returned as a tuple containing the key and its corresponding value.
The Dictionary is modified after removing the item.
Comparison of Dictionary Functions
| Function / Method | Purpose |
|---|---|
dict() |
Create a Dictionary. |
len() |
Returns the number of key-value pairs. |
get() |
Returns the value safely. |
pop() |
Removes the specified key and returns its value. |
popitem() |
Removes and returns one key-value pair. |
Real World Usage
These Dictionary functions are commonly used in:
- Student management systems.
- Employee databases.
- Configuration files.
- API response processing.
- Inventory management applications.
Important Notes
dict()creates a Dictionary.len()returns the total number of key-value pairs.get()is safer than using square brackets because it does not raiseKeyError.get()can return a custom default value.pop()removes a specified key and returns its value.popitem()removes and returns one key-value pair as a tuple.- Both
pop()andpopitem()modify the original Dictionary.
Quick Summary
| Method | Description |
|---|---|
dict() |
Create a Dictionary. |
len() |
Count key-value pairs. |
get() |
Return a value safely. |
pop() |
Remove a specified key. |
popitem() |
Remove one key-value pair. |
Dictionary Functions (Advanced)
Python provides several advanced Dictionary methods to access keys, values, items and to modify Dictionary objects.
In this part, we will learn:
keys()values()items()copy()setdefault()update()
keys() Method
The keys() method returns all keys present in the Dictionary.
The returned object can be used for iteration.
Syntax
main.py
No output captured.
Example
main.py
dict_keys([100, 200, 300])
values() Method
The values() method returns all values present in the Dictionary.
Syntax
main.py
No output captured.
Example
main.py
dict_values(['Durga', 'Ravi', 'Shiva'])
items() Method
The items() method returns all key-value pairs.
Each item is returned as a tuple.
Syntax
main.py
No output captured.
Example
main.py
dict_items([
(100, 'Durga'),
(200, 'Ravi'),
(300, 'Shiva')
])Difference Between keys(), values() and items()
| Method | Returns |
|---|---|
keys() |
All keys. |
values() |
All values. |
items() |
Key-value pairs as tuples. |
copy() Method
The copy() method creates a copy of the Dictionary.
The copied Dictionary is a new object.
The original Dictionary remains unchanged.
Syntax
main.py
No output captured.
Example
main.py
{100: 'Durga', 200: 'Ravi'}setdefault() Method
The setdefault() method returns the value associated with the specified key.
If the key is not available, it inserts the key with the specified default value and returns that value.
Syntax
main.py
No output captured.
Example 1 - Existing Key
main.py
Durga
{100: 'Durga', 200: 'Ravi'}Example 2 - New Key
main.py
Shiva
{100: 'Durga', 200: 'Ravi', 300: 'Shiva'}Important Notes - setdefault()
- If the key exists, its value is returned.
- If the key does not exist, a new key-value pair is created.
- The method returns the corresponding value.
update() Method
The update() method adds multiple key-value pairs from another Dictionary.
If a key already exists, its value is updated.
Syntax
main.py
No output captured.
Example
main.py
{
100: 'Durga',
200: 'Sunny',
300: 'Shiva',
400: 'Pavan'
}Explanation
The key 200 already exists in the first Dictionary.
Therefore, its value is updated.
The remaining key-value pairs are added as new entries.
Comparison of Advanced Dictionary Methods
| Method | Purpose |
|---|---|
keys() |
Returns all keys. |
values() |
Returns all values. |
items() |
Returns key-value pairs. |
copy() |
Creates a copy of the Dictionary. |
setdefault() |
Returns a value or inserts a new key. |
update() |
Adds or updates multiple key-value pairs. |
Real World Usage
These methods are commonly used in:
- Student information systems.
- Inventory management.
- Employee databases.
- API response processing.
- Configuration management.
Important Notes
keys()returns all keys.values()returns all values.items()returns key-value pairs as tuples.copy()creates a new Dictionary object.setdefault()adds a new key only if it is not already present.update()adds new entries and updates existing ones.update()modifies the original Dictionary.copy()does not modify the original Dictionary.
Quick Summary
| Method | Description |
|---|---|
keys() |
Returns all keys. |
values() |
Returns all values. |
items() |
Returns key-value pairs. |
copy() |
Creates a copy. |
setdefault() |
Returns or inserts a value. |
update() |
Adds or updates entries. |
Traversing a Dictionary
We can traverse a Dictionary by using a for loop.
By default, when we iterate over a Dictionary, only the keys are returned.
If we want the corresponding values, we can access them by using the key.
Example - Traversing a Dictionary
main.py
100 200 300
Explanation
The for loop traverses the Dictionary.
By default, each iteration returns only the key.
The values are not displayed unless they are accessed explicitly.
Traversing Dictionary Keys
We can use the keys() method to traverse all keys present in the Dictionary.
The keys() method returns a view object containing all keys.
Syntax
main.py
No output captured.
Example
main.py
dict_keys([100, 200, 300]) 100 200 300
Explanation
The keys() method returns all keys in the Dictionary.
The for loop prints each key one by one.
Traversing Dictionary Values
We can use the values() method to traverse all values present in the Dictionary.
The values() method returns a view object containing all values.
Syntax
main.py
No output captured.
Example
main.py
dict_values(['durga', 'ravi', 'shiva']) durga ravi shiva
Explanation
The values() method returns all values stored in the Dictionary.
The for loop prints each value one by one.
Traversing Key-Value Pairs
We can use the items() method to traverse both keys and values together.
The items() method returns key-value pairs as tuples.
Syntax
main.py
No output captured.
Example
main.py
100 -- durga 200 -- ravi 300 -- shiva
Explanation
The items() method returns each Dictionary item as a tuple.
The first variable stores the key and the second variable stores the corresponding value.
This is the most commonly used method for traversing a Dictionary when both keys and values are required.
Comparison of Dictionary Traversal Methods
| Method | Returns | Best Use |
|---|---|---|
for k in d |
Keys | Traverse only keys. |
d.keys() |
All keys | Display or process only keys. |
d.values() |
All values | Display or process only values. |
d.items() |
Key-value tuples | Access both keys and values together. |
Real-World Applications
Dictionary traversal is commonly used in:
- Displaying student records.
- Processing employee information.
- Reading configuration settings.
- Generating reports.
- Processing API response data.
Important Notes
- By default, iterating over a Dictionary returns only the keys.
keys()returns all keys in the Dictionary.values()returns all values in the Dictionary.items()returns key-value pairs as tuples.items()is the best choice when both keys and values are required.- Dictionary traversal is performed by using a
forloop.
Quick Summary
| Traversal | Description |
|---|---|
for k in d |
Traverses keys. |
d.keys() |
Returns all keys. |
d.values() |
Returns all values. |
d.items() |
Returns key-value pairs as tuples. |
Program - Find the Sum of Dictionary Values
In many real-world applications, we need to calculate the total of all numeric values stored in a Dictionary.
Python provides the built-in sum() function, which makes this task very simple.
In this program, the Dictionary is entered from the keyboard, and the sum of all its values is displayed.
Question
Write a Python program to take a Dictionary from the keyboard and print the sum of all its values.
Program
main.py
No output captured.
Sample Output
Understanding the Program
Let us understand the program step by step.
Step 1 - Read Dictionary from Keyboard
input()reads the Dictionary as a string.eval()converts the entered string into an actual Dictionary object.- The Dictionary is stored in the variable
d.
main.py
No output captured.
Example Input
main.py
No output captured.
Dictionary Created
main.py
No output captured.
Step 2 - Get All Values
The values() method returns all values present in the Dictionary.
main.py
No output captured.
Example
main.py
dict_values([100, 200, 300])
Step 3 - Calculate the Sum
The sum() function adds all numeric values returned by d.values().
The result is stored in the variable s.
main.py
No output captured.
Calculation
main.py
No output captured.
Step 4 - Display the Result
main.py
Sum = 600
Complete Program Execution
| Step | Operation |
|---|---|
| 1 | Read the Dictionary from the keyboard. |
| 2 | Retrieve all values using values(). |
| 3 | Calculate the total using sum(). |
| 4 | Display the final sum. |
Another Example
main.py
240
Real-World Applications
This program is useful in many real-world situations.
- Calculating total student marks.
- Finding the total salary of employees.
- Calculating total sales.
- Summing product quantities.
- Preparing reports.
Important Notes
values()returns all values stored in the Dictionary.sum()adds all numeric values.- The values must be numeric (int or float).
eval()converts the entered string into a Dictionary object.- The returned value of
sum()is stored in a variable before printing.
Quick Summary
| Statement | Purpose |
|---|---|
eval(input()) |
Reads a Dictionary from the keyboard. |
d.values() |
Returns all values. |
sum() |
Calculates the total of all values. |
print() |
Displays the result. |
Program - Count the Occurrence of Each Character
One of the most common applications of a Dictionary is counting the frequency of characters in a string.
In this program, each character is stored as a key and its number of occurrences is stored as the corresponding value.
If the character already exists in the Dictionary, its count is increased by 1. Otherwise, a new key is created with the value 1.
Question
Write a Python program to count the occurrence of each character present in a given string by using a Dictionary.
Program
main.py
No output captured.
Sample Output
Understanding the Program
Let us understand the program step by step.
Step 1 - Read the Input String
The input() function reads a string from the keyboard and stores it in the variable word.
main.py
No output captured.
Example Input
main.py
No output captured.
Step 2 - Create an Empty Dictionary
main.py
No output captured.
Explanation
The Dictionary d is initially empty.
It will store:
- Character → Key
- Frequency → Value
Step 3 - Traverse Each Character
main.py
No output captured.
Explanation
The for loop reads one character at a time from the string.
Each character is processed individually.
Step 4 - Count the Frequency
main.py
No output captured.
Explanation
The get() method checks whether the character already exists in the Dictionary.
- If the character exists, its current count is returned.
- If the character does not exist,
0is returned. - Then
1is added to the count.
This statement creates a new entry for a new character and updates the count for an existing character.
How the Dictionary Changes
main.py
No output captured.
Step 5 - Display the Result
main.py
No output captured.
Explanation
The items() method returns all key-value pairs.
The first variable stores the character and the second variable stores its frequency.
The program prints the frequency of every character.
Another Example
main.py
A occurred 1 times P occurred 2 times L occurred 1 times E occurred 1 times
Program Flow
| Step | Operation |
|---|---|
| 1 | Read the input string. |
| 2 | Create an empty Dictionary. |
| 3 | Traverse every character. |
| 4 | Increase the character count using get(). |
| 5 | Display all characters and their frequencies. |
Real-World Applications
This program is useful in many applications such as:
- Word frequency analysis.
- Text processing.
- Search engines.
- Natural Language Processing (NLP).
- Data analysis.
- Password strength checking.
Summary
| Statement | Purpose |
|---|---|
input() |
Read the input string. |
{} |
Create an empty Dictionary. |
for ch in word |
Traverse each character. |
get(ch, 0) |
Return the current count or 0. |
items() |
Return all key-value pairs. |
Important Notes
- A Dictionary is used to store character-frequency pairs.
- Each character acts as a key.
- The occurrence count acts as the value.
get(ch, 0)preventsKeyError.- The count is increased by one every time the character appears.
items()is used to print both the character and its frequency.- This is one of the most important Dictionary interview programs.
Program - Student Marks Lookup
Dictionary is one of the best data structures for storing data as key-value pairs.
In this program, the student name is stored as the key and the student marks are stored as the corresponding value.
The program allows the user to search for the marks of any student by entering the student's name.
Question
Write a Python program to store student names and marks in a Dictionary and display the marks based on the student name entered by the user.
Program
main.py
No output captured.
Sample Output
Understanding the Program
- An empty Dictionary is created.
- Student names are stored as keys.
- Student marks are stored as values.
- The
get()method searches for the student's marks. - If the student name is not found,
"Student Not Found"is displayed. - The user can search repeatedly until No is entered.
Dictionary Comprehension
Comprehension concept is applicable for Dictionaries also.
Dictionary Comprehension provides a simple and compact way to create Dictionary objects.
Syntax
main.py
No output captured.
Example 1
main.py
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}Explanation
The Dictionary stores:
- Key → Number
- Value → Square of that number
Example 2
main.py
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}Explanation
The Dictionary stores:
- Key → Number
- Value → Double of that number
Complete Summary of Dictionary Data Structure
| Topic | Description |
|---|---|
| Dictionary | Collection of key-value pairs. |
| Duplicate Keys | Not Allowed. |
| Duplicate Values | Allowed. |
| Heterogeneous Keys | Allowed. |
| Heterogeneous Values | Allowed. |
| Insertion Order | Not Preserved. |
| Mutable | Yes. |
| Dynamic | Yes. |
| Indexing | Not Supported. |
| Slicing | Not Supported. |
| Access Data | Using Keys. |
| get() | Returns the value for a key or a default value. |
| len() | Returns the number of key-value pairs. |
| pop() | Removes the specified key and returns its value. |
| popitem() | Removes and returns an arbitrary key-value pair. |
| keys() | Returns all keys. |
| values() | Returns all values. |
| items() | Returns all key-value pairs. |
| copy() | Creates a cloned copy. |
| setdefault() | Adds a key if it does not exist. |
| update() | Copies items from another Dictionary. |
| Dictionary Comprehension | Supported. |
Important Notes
- A Dictionary stores data as key-value pairs.
- Duplicate keys are not allowed.
- Duplicate values are allowed.
- Dictionary objects are mutable.
- Dictionary objects are dynamic.
- Dictionary elements are accessed by using keys, not indexes.
- The
get()method preventsKeyErrorby returning a default value when the key is not found. keys(),values()anditems()are commonly used while traversing a Dictionary.setdefault()adds a new key only if it is not already present.update()copies all key-value pairs from another Dictionary.- Python supports Dictionary Comprehension.
- Dictionary Comprehension provides a compact way to create Dictionary objects from iterable objects.