Nearby lessons
67 of 159Python - Dictionaries
- Understand what a dictionary is and how it stores key-value pairs
- Create and access dictionaries using the dict() function, get() and the in operator
- Add, update and remove key-value pairs
- Use dictionary methods like keys(), values(), items(), pop() and setdefault()
- Traverse dictionaries and write real-world programs
- Write dictionary comprehensions
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 preserved (Python 3.7+).
- 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
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
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
Feature 4 - Heterogeneous Keys and Values are Allowed
A Dictionary can store different types of keys and values.
Example
Feature 5 - Insertion Order is Preserved
Since Python 3.7, a Dictionary preserves the insertion order.
When we iterate a Dictionary or print it, the key-value pairs appear in the same order in which they were inserted.
The keys() method also returns the keys in 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
Example
Adding Key-Value Pairs
After creating an empty Dictionary, we can add key-value pairs one by one.
Example
Method 2 - Creating a Dictionary with Known Data
If the data is already known, we can directly create a Dictionary.
Syntax
Example
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
Example 1 - Access Existing Values
Explanation
The Dictionary searches for the specified key.
If the key exists, the corresponding value is returned.
Example 2 - Access a Missing Key
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
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
Example 1 - Add New Entry
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
Example 2 - Update Existing Value
Explanation
The key 200 already exists.
Therefore, only its value is updated.
Example 3 - Add and Update Together
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
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
Example 1 - Create an Empty Dictionary
Example 2 - Create Dictionary from Key-Value Pairs
len() Function
The len() function returns the total number of key-value pairs available in a Dictionary.
Syntax
Example 1 - Count Entries
Example 2 - Empty Dictionary
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
Example 1 - Existing Key
Example 2 - Missing Key
Example 3 - Default Value
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
Example 1 - Remove Existing Key
Example 2 - Remove Missing Key
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
Example
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.
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
Example
values() Method
The values() method returns all values present in the Dictionary.
Syntax
Example
items() Method
The items() method returns all key-value pairs.
Each item is returned as a tuple.
Syntax
Example
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
Example
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
Example 1 - Existing Key
Example 2 - New Key
update() Method
The update() method adds multiple key-value pairs from another Dictionary.
If a key already exists, its value is updated.
Syntax
Example
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.
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
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
Example
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
Example
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
Example
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.
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
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.
Example Input
Dictionary Created
Step 2 - Get All Values
The values() method returns all values present in the Dictionary.
Example
Step 3 - Calculate the Sum
The sum() function adds all numeric values returned by d.values().
The result is stored in the variable s.
Calculation
Step 4 - Display the Result
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
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.
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
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.
Example Input
Step 2 - Create an Empty Dictionary
Explanation
The Dictionary d is initially empty.
It will store:
- Character → Key
- Frequency → Value
Step 3 - Traverse Each Character
Explanation
The for loop reads one character at a time from the string.
Each character is processed individually.
Step 4 - Count the Frequency
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
Step 5 - Display the Result
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
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.
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
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
Example 1
Explanation
The Dictionary stores:
- Key → Number
- Value → Square of that number
Example 2
Explanation
The Dictionary stores:
- Key → Number
- Value → Double of that number
- A dictionary stores data as key-value pairs and duplicate keys are not allowed
- Dictionaries preserve insertion order in Python 3.7+
- Access values by key with d[key], get() or the in operator
- keys(), values() and items() return the dictionary's data
- Dictionary comprehensions build dictionaries in one expression