0% found this document useful (0 votes)
3 views20 pages

Python Module 4

This document covers Python collections, specifically focusing on lists, their creation, manipulation, and sorting methods. It explains various operations such as adding, updating, and removing elements, as well as searching algorithms like linear and binary search. Additionally, it discusses the differences between the sort() method and the sorted() function, along with examples of their usage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Python Module 4

This document covers Python collections, specifically focusing on lists, their creation, manipulation, and sorting methods. It explains various operations such as adding, updating, and removing elements, as well as searching algorithms like linear and binary search. Additionally, it discusses the differences between the sort() method and the sorted() function, along with examples of their usage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CAD 2201 PYTHON PROGRAMMING

MODULE IV PYTHON COLLECTIONS 9


Lists, List assignment, list bounds, slicing, list and functions, generation with list, sorting,
flexible sorting, search, linear search, binary search, list permutation, random permutation,
objects, string objects, list objects, Tuples & its operations, Dictionaries & its operations.

Python Lists
In Python, a list is a built-in data structure that can hold an ordered collection of items. Unlike
arrays in some languages, Python lists are very flexible:
• Can contain duplicate items
• Mutable: items can be modified, replaced, or removed
• Ordered: maintains the order in which items are added
• Index-based: items are accessed using their position (starting from 0)
• Can store mixed data types (integers, strings, booleans, even other lists)

Creating a List
Lists can be created in several ways, such as using square brackets, the list() constructor or by
repeating elements. Let's look at each method one by one with example:
1. Using Square Brackets
We use square brackets [] to create a list directly.
a = [1, 2, 3, 4, 5] # List of integers
b = ['apple', 'banana', 'cherry'] # List of strings
c = [1, 'hello', 3.14, True] # Mixed data types

print(a)
print(b)
print(c)

Output
[1, 2, 3, 4, 5]
['apple', 'banana', 'cherry']
[1, 'hello', 3.14, True]
2. Using list() Constructor
We can also create a list by passing an iterable (like a tuple, string or another list) to
the list() function.
a = list((1, 2, 3, 'apple', 4.5))
print(a)

b = list("GFG")
print(b)

Output
[1, 2, 3, 'apple', 4.5]
['G', 'F', 'G']
3. Creating List with Repeated Elements
We can use the multiplication operator * to create a list with repeated items.
a = [2] * 5
b = [0] * 7

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

print(a)
print(b)

Output
[2, 2, 2, 2, 2]
[0, 0, 0, 0, 0, 0, 0]

Accessing List Elements


Elements in a list are accessed using indexing. Python indexes start at 0, so a[0] gives the first
element. Negative indexes allow access from the end (e.g., -1 gives the last element).
a = [10, 20, 30, 40, 50]
print(a[0])
print(a[-1])
print(a[1:4]) # elements from index 1 to 3

Output
10
50
[20, 30, 40]

Adding Elements into List


We can add elements to a list using the following methods:
• append(): Adds an element at the end of the list.
• extend(): Adds multiple elements to the end of the list.
• insert(): Adds an element at a specific position.
• clear(): removes all items.
a = []

[Link](10)
print("After append(10):", a)

[Link](0, 5)
print("After insert(0, 5):", a)

[Link]([15, 20, 25])


print("After extend([15, 20, 25]):", a)

[Link]()
print("After clear():", a)

Output
After append(10): [10]
After insert(0, 5): [5, 10]
After extend([15, 20, 25]): [5, 10, 15, 20, 25]
After clear(): []

Updating Elements into List


Since lists are mutable, we can update elements by accessing them via their index.

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

a = [10, 20, 30, 40, 50]


a[1] = 25
print(a)

Output
[10, 25, 30, 40, 50]

Removing Elements from List


We can remove elements from a list using:
• remove(): Removes the first occurrence of an element.
• pop(): Removes the element at a specific index or the last element if no index is
specified.
• del statement: Deletes an element at a specified index.
a = [10, 20, 30, 40, 50]

[Link](30)
print("After remove(30):", a)

popped_val = [Link](1)
print("Popped element:", popped_val)
print("After pop(1):", a)

del a[0]
print("After del a[0]:", a)

Output
After remove(30): [10, 20, 40, 50]
Popped element: 20
After pop(1): [10, 40, 50]
After del a[0]: [40, 50]

Iterating Over Lists


We can iterate over lists using loops, which is useful for performing actions on each item.
a = ['apple', 'banana', 'cherry']
for item in a:
print(item)

Output
apple
banana
cherry

Nested Lists
A nested list is a list within another list, which is useful for representing matrices or tables. We
can access nested elements by chaining indexes.
matrix = [ [1, 2, 3],
[4, 5, 6],
[7, 8, 9] ]
print(matrix[1][2])

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

Output
6

LIST Comprehension
List comprehension is a concise way to create lists using a single line of code. It is useful for
applying an operation or filter to items in an iterable, such as a list or range.
squares = [x**2 for x in range(1, 6)]
print(squares)

Output
[1, 4, 9, 16, 25]
Explanation:
• for x in range(1, 6): loops through each number from 1 to 5 (excluding 6).
• x**2: squares each number x.
• [ ]: collects all the squared numbers into a new list.

How Python Stores List Elements?


In Python, a list doesn’t store actual values directly. Instead, it stores references (pointers) to
objects in memory. This means numbers, strings and booleans are separate objects in memory
and the list just keeps their addresses.
That’s why modifying a mutable element (like another list or dictionary) can change the
original object, while immutables remain unaffected.
a = [10, 20, "GfG", 40, True]
print(a)
print(a[0])
print(a[1])
print(a[2])

Output
[10, 20, 'GfG', 40, True]
10
20
GfG

Python sort() List Method


The sort() method in Python is a built-in function used to sort the elements of a list. It
arranges the elements in either ascending or descending order. The important feature of the
sort() method is that it performs in-place sorting, meaning it modifies the original list instead
of creating a new list.
The method can be used to sort numbers, strings, tuples, dictionaries and other objects that
support comparison operations.

Syntax
[Link](key=None, reverse=False)

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

Parameters of sort() Method


1. key (Optional Parameter)
The key parameter is used to specify a function that defines the sorting criteria.
• The function is applied to each element before sorting.
• If the key is not specified, Python sorts elements based on their natural order.
Example:
[Link](key=len)
This sorts words based on their length.

2. reverse (Optional Parameter)


The reverse parameter determines the order of sorting.
Value Meaning
False Ascending order (default)
True Descending order
Example:
[Link](reverse=True)

Return Value
The sort() method does not return a new list.
Instead, it returns None and modifies the original list directly.

Sorting in Ascending Order


By default, the sort() method arranges elements in ascending order.
Example
numbers = [4, 2, 9, 1, 5]

[Link]()

print(numbers)
Output
[1, 2, 4, 5, 9]

Sorting in Descending Order


To sort elements from largest to smallest, the reverse parameter is set to True.
Example
numbers = [4, 2, 9, 1, 5]

numbers. sort(reverse=True)

print(numbers)
Output
[9, 5, 4, 2, 1]

Custom Sorting Using key


The key parameter allows users to define custom sorting logic.
Sorting Strings by Length
words = ['apple', 'banana', 'cherry', 'date']

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

[Link](key=len)

print(words)
Output
['date', 'apple', 'cherry', 'banana']

Case-Insensitive Sorting
By default, sorting is [Link] perform case-insensitive sorting, the casefold()
method is used.
Example
words = ['apple', 'Banana', 'cherry', 'Date']

[Link](key=[Link])

print(words)

Sorting Tuples by Specific Element


Lists containing tuples can be sorted using a lambda function.
Example
students = [('Aarti','A',15), ('Raj','B',12), ('Simran','B',10)]

[Link](key=lambda x: x[2])

print(students)
Output
[('Simran','B',10), ('Raj','B',12), ('Aarti','A',15)]
Explanation:
Sorting is done based on the third element (age) of each tuple.

Sorting Using Multiple Criteria


Sorting can also be performed based on multiple conditions.
Example
items = [('apple',2), ('banana',1), ('cherry',2), ('date',1)]

[Link](key=lambda x: (x[1], x[0]))

print(items)
Output
[('banana',1), ('date',1), ('apple',2), ('cherry',2)]

sort() vs sorted() Function


Feature sort() sorted()
Modifies original list Yes No
Return value None New sorted list
Applicable to Lists only Any iterable
Memory usage Less More

Python sorted()

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

The Python sorted() function is a built-in utility that creates a new sorted list from the elements
of any iterable (such as a list, tuple, string, or dictionary) without modifying the original.
Syntax
The syntax for the sorted() function is:
python
sorted(iterable, key=None, reverse=False)
Parameters
• iterable (required): The object to be sorted (e.g., list, tuple, set, string, or dictionary).
• key (optional): A function that is called on each element to extract a comparison key.
The value returned by this function is used for sorting instead of the original element
value.
• reverse (optional): A boolean value. If True, the list is sorted in descending order. The
default is False (ascending order).
Examples
• Basic Usage (Ascending Order): By default, sorted() sorts numbers numerically and
strings alphabetically in ascending order.
numbers = [23, 42, 4, 8, 15, 16]
sorted_numbers = sorted(numbers)
print(sorted_numbers)
# Output: [4, 8, 15, 16, 23, 42]
print(numbers)
# Output: [23, 42, 4, 8, 15, 16] (original list remains unchanged)
• Descending Order: Use the reverse=True parameter to sort in descending order.

strs = ['banana', 'zebra', 'apple', 'donut']


sorted_strs = sorted(strs, reverse=True)
print(sorted_strs)
# Output: ['zebra', 'donut', 'banana', 'apple']
• Custom Sorting with key: The key parameter allows for customized sorting criteria.
For example, sorting a list of strings by their length using the built-in len function.
words = ['apple', 'banana', 'kiwi', 'cherry']
sorted_by_length = sorted(words, key=len)
print(sorted_by_length)
# Output: ['kiwi', 'apple', 'banana', 'cherry']
• Sorting Complex Objects: Use a lambda function or [Link] with
the key parameter to sort a list of dictionaries or tuples based on a specific attribute or
index.
students = [
{'name': 'Bob', 'age': 30},
{'name': 'Alice', 'age': 25},
{'name': 'Charlie', 'age': 28}
]
# Sort by age using a lambda function
sorted_students = sorted(students, key=lambda student: student['age'])
print(sorted_students)
# Output: [{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 28}, {'name':
'Bob', 'age': 30}]

sorted() vs. [Link]()

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

Python provides two methods for sorting. The primary difference is how they handle the
original data:
• sorted() (function): Returns a new sorted list and accepts any iterable as input. The
original iterable is unchanged.
• [Link]() (method): Modifies the original list in-place and returns None to avoid
confusion. It is a method of the list class and can only be used with lists.
When to Use sort() and sorted()
Use sort() when:
• You want to modify the original list
• You are working specifically with lists
• Memory efficiency is required
Use sorted() when:
• The original data must remain unchanged
• Sorting tuples, sets, or strings
• You need a new sorted list

Searching Algorithms in Python


Searching algorithms are fundamental techniques used to find an element or a value within a
collection of data. In this tutorial, we'll explore some of the most commonly used searching
algorithms in Python. These algorithms include Linear Search, Binary Search, Interpolation
Search, and Jump Search.
1. Linear Search
Linear search is the simplest searching algorithm. It sequentially checks each element of the
list until it finds the target value.
Steps:
• Start from the first element of the list.
• Compare each element of the list with the target value.
• If the element matches the target value, return its index.
• If the target value is not found after iterating through the entire list, return -1.
Implementation of Linear Search in Python:
def linear_search(arr, target):
"""
Perform linear search to find the target value in the given list.

Parameters:
arr (list): The list to be searched.
target: The value to be searched for.

Returns:
int: The index of the target value if found, otherwise -1.
"""
for i in range(len(arr)):
if arr[i] == target:
return i
return -1

# Example usage:

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

arr = [2, 3, 4, 10, 40]


target = 10
result = linear_search(arr, target)
if result != -1:
print(f"Linear Search: Element found at index {result}")
else:
print("Linear Search: Element not found")

Output
Linear Search: Element found at index 3

2. Binary Search
Binary search is a more efficient searching algorithm suitable for sorted lists. It repeatedly
divides the search interval in half until the target value is found.
Steps:
1. Start with the entire sorted list.
2. Compute the middle element of the list.
3. If the middle element is equal to the target value, return its index.
4. If the middle element is less than the target value, search in the right half of the list.
5. If the middle element is greater than the target value, search in the left half of the list.
6. Repeat steps 2-5 until the target value is found or the search interval is empty.
Implementation of Binary Search in Python (Recursive):
def binary_search(arr, target, low, high):
"""
Perform binary search recursively to find the target value in the given sorted list.

Parameters:
arr (list): The sorted list to be searched.
target: The value to be searched for.
low (int): The lower index of the search interval.
high (int): The upper index of the search interval.

Returns:
int: The index of the target value if found, otherwise -1.
"""
if low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
return binary_search(arr, target, mid + 1, high)
else:
return binary_search(arr, target, low, mid - 1)
else:
return -1

# Example usage:
arr = [2, 3, 4, 10, 40]
target = 10
result = binary_search(sorted(arr), target, 0, len(arr) - 1)

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

if result != -1:
print(f"Binary Search: Element found at index {result}")
else:
print("Binary Search: Element not found")

Output
Binary Search: Element found at index 3

List Permutation
Permutation means arranging the elements of a list in all possible orders.
In Python, permutations of a list can be generated using the itertools module.
Syntax
import itertools
[Link](iterable)
Example
import itertools

lst = [1, 2, 3]

perm = list([Link](lst))

print(perm)
Output
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

Random Permutation
A random permutation means randomly rearranging the elements of a list.
This can be done using the [Link]() function.
Syntax
import random
[Link](list)
Example
import random

lst = [1, 2, 3, 4, 5]

[Link](lst)

print(lst)
Possible Output
[3, 1, 5, 2, 4]

Difference Between List Permutation and Random Permutation


Feature List Permutation Random Permutation
Meaning All possible arrangements One random arrangement
Module itertools random

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

Feature List Permutation Random Permutation


Function permutations() shuffle()
Output Many combinations Single random order

Python Tuples
A tuple in Python is an immutable ordered collection of elements.
• Tuples are similar to lists, but unlike lists, they cannot be changed after their creation
(i.e., they are immutable).
• Tuples can hold elements of different data types.
• The main characteristics of tuples are being ordered, heterogeneous and immutable.
Creating a Tuple
A tuple is created by placing all the items inside parentheses (), separated by commas. A tuple
can have any number of items and they can be of different data types.
tup = ()
print(tup)

# Using String
tup = ('Geeks', 'For')
print(tup)

# Using List
li = [1, 2, 4, 5, 6]
print(tuple(li))

# Using Built-in Function


tup = tuple('Geeks')
print(tup)

Output
()
('Geeks', 'For')
(1, 2, 4, 5, 6)
('G', 'e', 'e', 'k', 's')
Let's understand tuple in detail:

Creating a Tuple with Mixed Datatypes.


Tuples can contain elements of various data types, including other tuples, lists, dictionaries and
even functions.
tup = (5, 'Welcome', 7, 'Geeks')
print(tup)

# Creating a Tuple with nested tuples


tup1 = (0, 1, 2, 3)
tup2 = ('python', 'geek')
tup3 = (tup1, tup2)
print(tup3)

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

# Creating a Tuple with repetition


tup1 = ('Geeks',) * 3
print(tup1)

Output
(5, 'Welcome', 7, 'Geeks')
((0, 1, 2, 3), ('python', 'geek'))
('Geeks', 'Geeks', 'Geeks')

Python Tuple Basic Operations


Below are the Python tuple operations.
• Accessing of Python Tuples
• Concatenation of Tuples
• Slicing of Tuple
• Deleting a Tuple
Accessing of Tuples
We can access the elements of a tuple by using indexing and slicing, similar to how we access
elements in a list. Indexing starts at 0 for the first element and goes up to n-1, where n is the
number of elements in the tuple. Negative indexing starts from -1 for the last element and goes
backward.
# Accessing Tuple with Indexing
tup = tuple("Geeks")
print(tup[0])

# Accessing a range of elements using slicing


print(tup[1:4])
print(tup[:3])

# Tuple unpacking
tup = ("Geeks", "For", "Geeks")

# This line unpack values of Tuple1


a, b, c = tup
print(a)
print(b)
print(c)

Output
G
('e', 'e', 'k')
('G', 'e', 'e')
Geeks
For
Geeks

Concatenation of Tuples

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

Tuples can be concatenated using the + operator. This operation combines two or more tuples
to create a new tuple.
Note: Only the same datatypes can be combined with concatenation, an error arises if a list
and a tuple are combined.

tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')

tup3 = tup1 + tup2


print(tup3)

Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')

Slicing of Tuple
Slicing a tuple means creating a new tuple from a subset of elements of the original tuple. The
slicing syntax is tuple[start:stop:step].
Note: Negative Increment values can also be used to reverse the sequence of Tuples.

tup = tuple('GEEKSFORGEEKS')

# Removing First element


print(tup[1:])

# Reversing the Tuple


print(tup[::-1])

# Printing elements of a Range


print(tup[4:9])

Output
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')
('S', 'F', 'O', 'R', 'G')

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

Note: [:] returns a shallow copy of the tuple, while [::step] allows stepping through elements.
Using [::-1] reverses the sequence.

Deleting a Tuple
Since tuples are immutable, we cannot delete individual elements of a tuple. However, we can
delete an entire tuple using del statement.
Note: Printing of Tuple after deletion results in an Error.
Tup = (0, 1, 2, 3, 4)
del tup

print(tup)
Output
ERROR!
Traceback (most recent call last):
File “<[Link]>”, line 6, in <module>
NameError: name ‘tup’ is not defined

Tuple Unpacking with Asterisk (*)


In Python, the " * " operator can be used in tuple unpacking to grab multiple items into a list.
This is useful when you want to extract just a few specific elements and collect the rest together.
tup = (1, 2, 3, 4, 5)

a, *b, c = tup

print(a)
print(b)
print(c)

Output
1
[2, 3, 4]
5
Explanation:
• a gets the first item.
• c gets the last item.

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

• *b collects everything in between into a list.

Python Dictionary
A Python dictionary is a data structure that stores data in key-value pairs, where each key is
unique and is used to retrieve its associated value. It is mainly used when you want to store and
access data by a name (key) instead of by position like in a list.
Example: This example shows how a dictionary stores data using keys and values.
data = { "name": "Jake", "age": 22 }
print(data)

Output
{'name': 'Jake', 'age': 22}
Explanation:
• "name" and "age" are keys
• "Jake" and 22 are their values
• dictionary stores data in key : value format

Creating a Dictionary
A dictionary is created by writing key-value pairs inside { }, where each key is connected to a
value using colon (:). A dictionary can also be created using the dict() function.
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)

# using dict() constructor


d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)

Output

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

{1: 'Geeks', 2: 'For', 3: 'Geeks'}


{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
Accessing Dictionary Items
A value in a dictionary is accessed by using its key. This can be done either with square brackets
[ ] or with the get() method. Both return the value linked to the given key.
d = { "name": "Kat", 1: "Python", (1, 2): [1,2,4] }

# Access using key


print(d["name"])

# Access using get()


print([Link]("name"))

Output
Kat
Kat
Adding and Updating Dictionary Items
New items are added to a dictionary using the assignment operator (=) by giving a new key a
value. If an existing key is used with the assignment operator, its value is updated with the new
one.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

# Adding a new key-value pair


d["age"] = 22

# Updating an existing value


d[1] = "Python dict"
print(d)

Output
{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
Removing Dictionary Items
Dictionary items can be removed using built-in deletion methods that work on keys:
• del: removes an item using its key
• pop(): removes the item with the given key and returns its value
• clear(): removes all items from the dictionary
• popitem(): removes and returns the last inserted key–value pair
d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}

# Using del
del d["age"]
print(d)

# Using pop()
val = [Link](1)
print(val)

# Using popitem()
key, val = [Link]()
print(f"Key: {key}, Value: {val}")

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

# Using clear()
[Link]()
print(d)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
Key: 3, Value: Geeks
{}
Iterating Through a Dictionary
A dictionary can be traversed using a for loop to access its keys, values or both key-value pairs
by using the built-in methods keys(), values() and items().
d = {1: 'Geeks', 2: 'For', 'age':22}

# Iterate over keys


for key in d:
print(key)

# Iterate over values


for value in [Link]():
print(value)

# Iterate over key-value pairs


for key, value in [Link]():
print(f"{key}: {value}")

Output
1
2
age
Geeks
For
22
1: Geeks
2: For
age: 22

Nested Dictionaries
A nested dictionary is a dictionary that contains another dictionary as one of its values. Below
diagram shows how a nested dictionary works, where key 3 points to another dictionary inside
the main dictionary.

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

Representation of Nested Dictionary


The arrows show how each key is connected to its corresponding value.
d = {1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
print(d)
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

Built-in Dictionary Methods in Python


In Python Dictionary we have various built-in functions that provide a wide range of operations
for working with dictionaries. These techniques enable efficient manipulation, access, and
transformation of dictionary data.
Lets Look at some Python dictionary methods with examples:
1. Dictionary clear() Method
The clear() method in Python is a built-in method that is used to remove all the elements (key-
value pairs) from a dictionary. It essentially empties the dictionary, leaving it with no key-value
pairs.
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)

Output
{}
2. Dictionary get() Method
In Python, the get() method is a pre-built dictionary function that enables you to obtain the
value linked to a particular key in a dictionary. It is a secure method to access dictionary values
without causing a KeyError if the key isn't present.
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print([Link]('Name'))
print([Link]('Gender'))

Output
Ram
None
3. Dictionary items() Method
In Python, the items() method is a built-in dictionary function that retrieves a view object
containing a list of tuples. Each tuple represents a key-value pair from the dictionary. This
method is a convenient way to access both the keys and values of a dictionary simultaneously,
and it is highly efficient.
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list([Link]())[1][0])

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

print(list([Link]())[1][1])

Output
Age
19
4. Dictionary keys() Method
The keys() method in Python returns a view object with dictionary keys, allowing efficient
access and iteration.
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list([Link]()))

Output
['Name', 'Age', 'Country']
5. Dictionary update() Method
Python's update() method is a built-in dictionary function that updates the key-value pairs of a
dictionary using elements from another dictionary or an iterable of key-value pairs. With this
method, you can include new data or merge it with existing dictionary entries.
d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d2 = {'Name': 'Neha', 'Age': '22'}

[Link](d2)
print(d1)

Output
{'Name': 'Neha', 'Age': '22', 'Country': 'India'}
6. Dictionary values() Method
The values() method in Python returns a view object containing all dictionary values, which
can be accessed and iterated through efficiently.
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list([Link]()))

Output
['Ram', '19', 'India']
7. Dictionary pop() Method
In Python, the pop() method is a pre-existing dictionary method that removes and retrieves the
value linked with a given key from a dictionary. If the key is not present in the dictionary, you
can set an optional default value to be returned.
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
[Link]('Age')
print(d)

Output
{'Name': 'Ram', 'Country': 'India'}
8. Dictionary popitem() Method
The popitem() method in Python dictionaries is used to remove and return the last
inserted key-value pair as a tuple. If the dictionary is empty then it raises a KeyError.
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
val = [Link]()
print(val)

Dr Jose Reena K,BSACIST


CAD 2201 PYTHON PROGRAMMING

val = [Link]()
print(val)

Output
('Country', 'India')
('Age', '19')

Dr Jose Reena K,BSACIST

You might also like