Nearby lessons

67 of 159

Python - Dictionaries

📌 What You Will Learn
  • 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

🐍Code Cell
1dictionary = {
2 key1: value1,
3 key2: value2
4}
Output
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

🐍Code Cell
1d = {
2 101: "durga",
3 102: "ravi",
4 103: "shiva"
5}
6 
7d[101] = "sunny"
8 
9print(d)
Output
{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

🐍Code Cell
1d = {
2 101: "durga",
3 102: "durga",
4 103: "shiva"
5}
6 
7print(d)
Output
{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

🐍Code Cell
1d = {
2 100: "Durga",
3 "A": 10,
4 10.5: "Python",
5 True: "Yes"
6}
7 
8print(d)
Output
{100: 'Durga', 'A': 10, 10.5: 'Python', True: 'Yes'}

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.

🐍Code Cell
1d = {
2 100: "durga",
3 200: "ravi",
4 300: "shiva"
5}
6 
7print(d)
8 
9print(d.keys())
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}
dict_keys([100, 200, 300])

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

🐍Code Cell
1d = {}
2 
3# or
4 
5d = dict()
Output
No output captured.

Example

🐍Code Cell
1d = {}
2 
3print(d)
4 
5print(type(d))
Output
{}

Adding Key-Value Pairs

After creating an empty Dictionary, we can add key-value pairs one by one.

Example

🐍Code Cell
1d = {}
2 
3d[100] = "durga"
4d[200] = "ravi"
5d[300] = "shiva"
6 
7print(d)
Output
{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

🐍Code Cell
1d = {
2 key1: value1,
3 key2: value2
4}
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "durga",
3 200: "ravi",
4 300: "shiva"
5}
6 
7print(d)
Output
{100: 'durga', 200: 'ravi', 300: 'shiva'}

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

🐍Code Cell
1dictionary_name[key]
Output
No output captured.

Example 1 - Access Existing Values

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7print(d[100])
8 
9print(d[300])
Output
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

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6print(d[300])
Output
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

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7if 200 in d:
8 print(d[200])
9 
10if 500 in d:
11 print(d[500])
12else:
13 print("Key Not Found")
Output
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

🐍Code Cell
1dictionary_name[new_key] = value
Output
No output captured.

Example 1 - Add New Entry

🐍Code Cell
1d = {}
2 
3d[100] = "Durga"
4d[200] = "Ravi"
5d[300] = "Shiva"
6 
7print(d)
Output
{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

🐍Code Cell
1dictionary_name[existing_key] = new_value
Output
No output captured.

Example 2 - Update Existing Value

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7d[200] = "Sunny"
8 
9print(d)
Output
{100: 'Durga', 200: 'Sunny', 300: 'Shiva'}

Explanation

The key 200 already exists.

Therefore, only its value is updated.

Example 3 - Add and Update Together

🐍Code Cell
1d = {}
2 
3d[101] = "Amit"
4d[102] = "Rahul"
5 
6d[102] = "Karan"
7 
8d[103] = "Vijay"
9 
10print(d)
Output
{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

🐍Code Cell
1students = {}
2 
3students[101] = "Rahul"
4students[102] = "Amit"
5students[103] = "Neha"
6 
7print(students)
8 
9print("Student with Roll No 102 =", students[102])
10 
11students[102] = "Priya"
12 
13print("Updated Dictionary:")
14 
15print(students)
Output
{101: 'Rahul', 102: 'Amit', 103: 'Neha'}
Student with Roll No 102 = Amit
Updated Dictionary:
{101: 'Rahul', 102: 'Priya', 103: 'Neha'}

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

🐍Code Cell
1d = dict()
2 
3# or
4 
5d = dict(iterable)
Output
No output captured.

Example 1 - Create an Empty Dictionary

🐍Code Cell
1d = dict()
2 
3print(d)
4 
5print(type(d))
Output
{}

Example 2 - Create Dictionary from Key-Value Pairs

🐍Code Cell
1d = dict([
2 (100, "Durga"),
3 (200, "Ravi"),
4 (300, "Shiva")
5])
6 
7print(d)
Output
{100: 'Durga', 200: 'Ravi', 300: 'Shiva'}

len() Function

The len() function returns the total number of key-value pairs available in a Dictionary.

Syntax

🐍Code Cell
1len(dictionary)
Output
No output captured.

Example 1 - Count Entries

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7print(len(d))
Output
3

Example 2 - Empty Dictionary

🐍Code Cell
1d = {}
2 
3print(len(d))
Output
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

🐍Code Cell
1dictionary.get(key)
2 
3dictionary.get(key, default_value)
Output
No output captured.

Example 1 - Existing Key

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6print(d.get(100))
Output
Durga

Example 2 - Missing Key

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6print(d.get(300))
Output
None

Example 3 - Default Value

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6print(d.get(300, "Key Not Found"))
Output
Key Not Found

Advantages of get()

  • Prevents KeyError.
  • Returns None if 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

🐍Code Cell
1dictionary.pop(key)
Output
No output captured.

Example 1 - Remove Existing Key

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7print(d.pop(200))
8 
9print(d)
Output
Ravi
{100: 'Durga', 300: 'Shiva'}

Example 2 - Remove Missing Key

🐍Code Cell
1d = {
2 100: "Durga"
3}
4 
5print(d.pop(200))
Output
KeyError: 200

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

🐍Code Cell
1dictionary.popitem()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7print(d.popitem())
8 
9print(d)
Output
(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.

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

🐍Code Cell
1dictionary.keys()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7print(d.keys())
Output
dict_keys([100, 200, 300])

values() Method

The values() method returns all values present in the Dictionary.

Syntax

🐍Code Cell
1dictionary.values()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7print(d.values())
Output
dict_values(['Durga', 'Ravi', 'Shiva'])

items() Method

The items() method returns all key-value pairs.

Each item is returned as a tuple.

Syntax

🐍Code Cell
1dictionary.items()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi",
4 300: "Shiva"
5}
6 
7print(d.items())
Output
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

🐍Code Cell
1new_dictionary = dictionary.copy()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6d1 = d.copy()
7 
8print(d1)
Output
{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

🐍Code Cell
1dictionary.setdefault(key)
2 
3dictionary.setdefault(key, default_value)
Output
No output captured.

Example 1 - Existing Key

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6print(d.setdefault(100, "Sunny"))
7 
8print(d)
Output
Durga
{100: 'Durga', 200: 'Ravi'}

Example 2 - New Key

🐍Code Cell
1d = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6print(d.setdefault(300, "Shiva"))
7 
8print(d)
Output
Shiva
{100: 'Durga', 200: 'Ravi', 300: 'Shiva'}

update() Method

The update() method adds multiple key-value pairs from another Dictionary.

If a key already exists, its value is updated.

Syntax

🐍Code Cell
1dictionary.update(other_dictionary)
Output
No output captured.

Example

🐍Code Cell
1d1 = {
2 100: "Durga",
3 200: "Ravi"
4}
5 
6d2 = {
7 200: "Sunny",
8 300: "Shiva",
9 400: "Pavan"
10}
11 
12d1.update(d2)
13 
14print(d1)
Output
{
    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.

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

🐍Code Cell
1d = {
2 100: "durga",
3 200: "ravi",
4 300: "shiva"
5}
6 
7for k in d:
8 print(k)
Output
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

🐍Code Cell
1dictionary.keys()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "durga",
3 200: "ravi",
4 300: "shiva"
5}
6 
7print(d.keys())
8 
9for k in d.keys():
10 print(k)
Output
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

🐍Code Cell
1dictionary.values()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "durga",
3 200: "ravi",
4 300: "shiva"
5}
6 
7print(d.values())
8 
9for v in d.values():
10 print(v)
Output
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

🐍Code Cell
1dictionary.items()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 100: "durga",
3 200: "ravi",
4 300: "shiva"
5}
6 
7for k, v in d.items():
8 print(k, "--", v)
Output
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.

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

🐍Code Cell
1d = eval(input("Enter dictionary: "))
2 
3s = sum(d.values())
4 
5print("Sum =", s)
Output
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.
🐍Code Cell
1d = eval(input("Enter dictionary: "))
Output
No output captured.

Example Input

🐍Code Cell
1{'A':100,'B':200,'C':300}
Output
No output captured.

Dictionary Created

🐍Code Cell
1d = {
2 'A': 100,
3 'B': 200,
4 'C': 300
5}
Output
No output captured.

Step 2 - Get All Values

The values() method returns all values present in the Dictionary.

🐍Code Cell
1d.values()
Output
No output captured.

Example

🐍Code Cell
1d = {
2 'A': 100,
3 'B': 200,
4 'C': 300
5}
6 
7print(d.values())
Output
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.

🐍Code Cell
1s = sum(d.values())
Output
No output captured.

Calculation

🐍Code Cell
1100 + 200 + 300 = 600
Output
No output captured.

Step 4 - Display the Result

🐍Code Cell
1d = {
2 'A': 100,
3 'B': 200,
4 'C': 300
5}
6 
7s = sum(d.values())
8 
9print("Sum =", s)
Output
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

🐍Code Cell
1d = {
2 "Math": 80,
3 "Science": 90,
4 "English": 70
5}
6 
7print(sum(d.values()))
Output
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.

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

🐍Code Cell
1word = input("Enter Any String : ")
2 
3d = {}
4 
5for ch in word:
6 d[ch] = d.get(ch, 0) + 1
7 
8for k, v in d.items():
9 print(k, "occurred", v, "times")
Output
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.

🐍Code Cell
1word = input("Enter Any String : ")
Output
No output captured.

Example Input

🐍Code Cell
1MISSISSIPPI
Output
No output captured.

Step 2 - Create an Empty Dictionary

🐍Code Cell
1d = {}
Output
No output captured.

Explanation

The Dictionary d is initially empty.

It will store:

  • Character → Key
  • Frequency → Value

Step 3 - Traverse Each Character

🐍Code Cell
1for ch in word:
Output
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

🐍Code Cell
1d[ch] = d.get(ch, 0) + 1
Output
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, 0 is returned.
  • Then 1 is 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

🐍Code Cell
1Input : MISS
2 
3After M
4{'M': 1}
5 
6After I
7{'M': 1, 'I': 1}
8 
9After S
10{'M': 1, 'I': 1, 'S': 1}
11 
12After S
13{'M': 1, 'I': 1, 'S': 2}
Output
No output captured.

Step 5 - Display the Result

🐍Code Cell
1for k, v in d.items():
2 print(k, "occurred", v, "times")
Output
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

🐍Code Cell
1word = "APPLE"
2 
3d = {}
4 
5for ch in word:
6 d[ch] = d.get(ch, 0) + 1
7 
8for k, v in d.items():
9 print(k, "occurred", v, "times")
Output
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.

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

🐍Code Cell
1rec = {}
2 
3n = int(input("Enter number of students: "))
4 
5i = 1
6 
7while i <= n:
8 name = input("Enter Student Name: ")
9 marks = input("Enter Student Marks: ")
10 
11 rec[name] = marks
12 
13 i = i + 1
14 
15while True:
16 
17 name = input("Enter Student Name to get Marks: ")
18 
19 marks = rec.get(name, "Student Not Found")
20 
21 print("The Marks of", name, "are", marks)
22 
23 option = input("Do you want to find another student marks[Yes|No]")
24 
25 if option == "No":
26 break
27 
28print("Thanks for using our application")
Output
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

🐍Code Cell
1dictionary = {
2 key_expression : value_expression
3 for item in iterable
4}
Output
No output captured.

Example 1

🐍Code Cell
1squares = {x: x * x for x in range(1, 6)}
2 
3print(squares)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Explanation

The Dictionary stores:

  • Key → Number
  • Value → Square of that number

Example 2

🐍Code Cell
1doubles = {x: 2 * x for x in range(1, 6)}
2 
3print(doubles)
Output
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}

Explanation

The Dictionary stores:

  • Key → Number
  • Value → Double of that number
📝 Key Takeaways
  • 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

🧠 Test Your Knowledge

58 Questions
Progress: 0 / 58