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

Python m3

Uploaded by

shobaaji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Python m3

Uploaded by

shobaaji
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Python programming for Data Science

[BDS306B]
LECTURE NOTES
MODULE -3

Prepared by Anitha, Dept of AIML| SCE,Anekal |


PYTHON PROGRAMMING III YEAR/II SEM MRCET

2
PYTHON PROGRAMMING III YEAR/II SEM MRCET

LISTS, TUPLES, DICTIONARIES

Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
comprehension; Dictionaries: operations and methods, comprehension.
Lists have the following characteristics:
 Lists are ordered, meaning that the items have a defined order, and that order will not change unless
we modify the list1.
 Lists are changeable, meaning that we can add, remove, or modify items in a list after it has been
created1.
 Lists allow duplicate values, meaning that a list can have multiple items with the same value 1.
 Lists can contain items of any data type, such as strings, integers, booleans, or even other lists 1.

Lists, Tuples, Dictionaries:

List:

 It is a general purpose most widely used in data structures


 List is a collection which is ordered and changeable and allows duplicate members.
(Grow and shrink as needed, sequence type, sortable).
 To use a list, you must declare it first. Do this using square brackets and separate
values with commas.
 We can construct / create list in many
ways. Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]

>>> x=list()
>>> x
[]

3
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership

Basic List Operations:

Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
Assuming following input −
L = ['mrcet', 'college', 'MRCET!']

4
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Python Expression Results Description

L[2] MRCET Offsets start at zero

5
PYTHON PROGRAMMING III YEAR/II SEM MRCET
L[-2] college Negative: count from the right

L[1:] ['college', 'MRCET!'] Slicing fetches sections

List slices:

>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
[2, 4, 6, 8]
List methods:
The list data type has some more methods. Here are all of the methods of list objects:
 Del()
6
PYTHON PROGRAMMING III YEAR/II SEM MRCET
 Append()
 Extend()
 Insert()
 Pop()
 Remove()
 Reverse()
 Sort()
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]

>>> del(x)
>>> x # complete list gets deleted
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:

>>> x=[1,2,4,6,7]

7
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x.insert(2,10) #insert(index no, item to be inserted)

>>> x

[1, 2, 10, 4, 6, 7]

>>> x.insert(4,['a',11])

>>> x

[1, 2, 10, 4, ['a', 11], 6, 7]

Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.

>>> x=[1, 2, 10, 4, 6, 7]

>>> x.pop()

>>> x

[1, 2, 10, 4, 6]

>>> x=[1, 2, 10, 4, 6]

>>> x.pop(2)

10

>>> x

[1, 2, 4, 6]

Remove: The remove() method removes the specified item from a given list.

>>> x=[1,33,2,10,4,6]

>>> x.remove(33)

>>> x

8
PYTHON PROGRAMMING III YEAR/II SEM MRCET
[1, 2, 10, 4, 6]

>>> x.remove(4)

>>> x

[1, 2, 10, 6]

Reverse: Reverse the order of a given list.


>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]

>>> x.sort()

>>> x

[1, 2, 3, 4, 5, 6, 7]

>>> x=[10,1,5,3,8,7]

>>> x.sort()

>>> x

[1, 3, 5, 7, 8, 10]

List loop:

Loops are control structures used to repeat a given section of code a certain number of times
or until a particular condition is met.

Method #1: For loop

#list of items

list = ['M','R','C','E','T']
9
PYTHON PROGRAMMING III YEAR/II SEM MRCET
i=1

#Iterating over the list


for item in list:
print ('college ',i,' is ',item)
i = i+1
Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T

Method #2: For loop and range()


In case we want to use the traditional for loop which iterates from number x to number y.
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]

# getting length of list


length = len(list)

# Iterating the index


# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/listlooop.py
1
3
5
7
9
Method #3: using while loop

# Python3 code to iterate over a list


list = [1, 3, 5, 7, 9]

# Getting length of list


10
PYTHON PROGRAMMING III YEAR/II SEM MRCET
length = len(list)
i=0

# Iterating using while loop


while i < length:
print(list[i])
i += 1

Mutability:

A mutable object can be changed after it is created, and an immutable object can't.

Append: Append an item to a list


>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
Insert: To add an item at the specified index, use the insert () method:

>>> x=[1,2,4,6,7]

>>> x.insert(2,10) #insert(index no, item to be inserted)

11
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x

[1, 2, 10, 4, 6, 7]

>>> x.insert(4,['a',11])

>>> x

[1, 2, 10, 4, ['a', 11], 6, 7]

Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.

>>> x=[1, 2, 10, 4, 6, 7]

>>> x.pop()

>>> x

[1, 2, 10, 4, 6]

>>> x=[1, 2, 10, 4, 6]

>>> x.pop(2)

10

>>> x

[1, 2, 4, 6]

Remove: The remove() method removes the specified item from a given list.

>>> x=[1,33,2,10,4,6]

>>> x.remove(33)

>>> x

[1, 2, 10, 4, 6]

12
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x.remove(4)

>>> x

[1, 2, 10, 6]

Reverse: Reverse the order of a given list.


>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]

>>> x.sort()

>>> x

[1, 2, 3, 4, 5, 6, 7]

>>> x=[10,1,5,3,8,7]

>>> x.sort()

>>> x

[1, 3, 5, 7, 8, 10]

13
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Tuples

A tuple is a collection of ordered and unchangeable elements in Python. It is one of the four built-in
data types in Python used to store collections of data.

The characteristics of a Python tuple are:

1. Tuples are ordered, indexed collections of data. Similar to string indices, the first value in
the tuple will have the index [0], the second value [1], and so on.
2. Tuples can store duplicate values.
3. Once data is assigned to a tuple, the values cannot be changed.
4. Tuples allow you to store several data items in one variable. You can choose to store only
one kind of data in a tuple or mix it up as needed.

Creating Tuple

To create a tuple, we can use round brackets () and separate the elements by commas. For example:
my_tuple = ("apple", "banana", "cherry")
print(my_tuple) # ('apple', 'banana', 'cherry')

We can also create a tuple without using brackets, by just assigning values separated by commas to a
variable. For example:
my_tuple = 1, 2, 3
print(my_tuple) # (1, 2, 3)
To create a tuple with only one element, we need to add a comma after the element, otherwise Python will
not recognize it as a tuple1. For example:
my_tuple = ("apple",)
print(type(my_tuple))
Tuples can contain any data type, such as strings, integers, floats, booleans, lists, or other tuples 1. For
example:
my_tuple = ("abc", 34, True, 40.5, "male")
print(my_tuple) # ('abc', 34, True, 40.5, 'male')
create an empty tuple by putting no values between the brackets
tuple1 = ();
Using the tuple() constructor and passing an iterable object as an argument. For example: my_tuple =
tuple([1, 2, 3, "hello"])

Indexing and slicing in a tuple

In Python, every tuple with elements has a position or index. Each element of the tuple can be
accessed or manipulated by using the index number.

They are two types of indexing –


14
PYTHON PROGRAMMING III YEAR/II SEM MRCET

 Positive Indexing
 Negative Indexing

In positive the first element of the tuple is at an index of 0 and the following elements are at +1
and as follows.

In the below figure, we can see how an element in the tuple is associated with its index or
position.

Example 1

The following is an example code to show the positive indexing of tuples.

tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(3))
print(tuple(7)

Negative Indexing

In negative indexing, the indexing of elements starts from the end of the tuple. That is the last
element of the tuple is said to be at a position at -1 and the previous element at -2 and goes on
till the first element.

In the below figure, we can see how an element is associated with its index or position of a
tuple.

15
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Example

The following is an example code to show the negative indexing in tuples.

tuple= (5,2,9,7,5,8,1,4,3)
print(tuple(-2))
print(tuple(-8))

Slicing tuples
Slicing is used to access a range of elements in a tuple. We can represent the slicing
operator in the syntax [start:stop:step].
Moreover, it is not necessary to mention the ‘step’ part. The compiler considers it 1 by
default if we do not mention the step part.

 tup[0:6] will give us the 1st to 6th element of the tuple.


 tup[1:9:2] will give us the 2nd to 9th element of the tuple with a step of 2.
 tup[-1:-5:-2] will give us the last 2nd to 5th element of the tuple with a step of -2.
 tup[:] will give us the entire tuple.

Example 1

In the following example we have used the slice operation to slice a tuple. We also use negative
indexing method to slice a tuple.

tuple= ('a','b','c','d','e','f','g','h','i','j')
print(tuple[0:6])
print(tuple[1:9:2])
print(tuple[-1:-5:-2])
Output

The above code produces the following results

('a', 'b', 'c', 'd', 'e', 'f')

16
PYTHON PROGRAMMING III YEAR/II SEM MRCET
('b', 'd', 'f', 'h')
('j', 'h')

Example 2

Following is another example for this −

my_tuple = ('t', 'u', 'r', 'i', 'a', 'l', 's', 'p','o', 'i', 'n', 't')
print(my_tuple[1:]) #Print elements from index 1 to end
print(my_tuple[:2]) #Print elements from start to index 2
print(my_tuple[5:12]) #Print elements from index 1 to index 3
print(my_tuple[::5]) #Print elements from start to end using step size
Output
('u', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'u')
('l', 's', 'p', 'o', 'i', 'n', 't')
('t', 'l', 'n')

Tuples are more efficient than list due to python’s implementation.

We can construct tuple in many


ways: X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4

Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)

>>> x= [4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)

17
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)

Some of the operations of tuple are:


 Access tuple items
 Change tuple items
 Loop through a tuple
 Count()
 Index()
 Length()
 concatenation

Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])

Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.

>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same

Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)

4
5
18
PYTHON PROGRAMMING III YEAR/II SEM MRCET
6
7
2
aa

Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4

Index (): Searches the tuple for a specified value and returns the position of where it was
found
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2)
1

(Or)

>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1

Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12
Concatenate operation on tuples

Concatenation of tuples in python means joining two or more tuples to form a single tuple. The
'+' operator can be used to concatenate texts or add numeric values.

tuple_1 = (11, 14, 0, 78, 33, 11)


tuple_2 = (10, 78, 0, 56, 8, 34)
print("The first tuple is : ")
print(tuple_1)
print("The second tuple is : ")
print(tuple_2)
result = tuple_1 + tuple_2
print("The tuple after concatenation is : " )

19
PYTHON PROGRAMMING III YEAR/II SEM MRCET
print(result)

Repetition

When it is required to repeat a tuple 'N' times, the '*' operator can be used. The '*'
operator behaves like a multiplication operator.

my_tuple_1 = (11, 14, 0)

print("The tuple is : ")


print(my_tuple_1)
N = 5

my_result = ((my_tuple_1, ) * N)

print("The tuple after duplicating "+ str(N) + " times is")


print(my_result)

Membership
python's membership operators test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators as explained below

Operat Examp
Description
or le

x in y,
here in
results in
a 1 if x is
Evaluates to true if it finds a variable in the
in a
specified sequence and false otherwise.
member
of
sequence
y.

not in Evaluates to true if it does not finds a variable x not in


in the specified sequence and false otherwise. y, here
not in
results in
a 1 if x is
not a
member

20
PYTHON PROGRAMMING III YEAR/II SEM MRCET
of
sequence
y.
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"

if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"

a = 2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"

Tuple Assignment

Python has tuple assignment feature which enables you to assign more than one variable at a
time. In here, we have assigned tuple 1 with the college information like college name, year,
etc. and another tuple 2 with the values in it like number (1, 2, 3… 7).

For Example,

Here is the code,

 >>> tup1 = ('mrcet', 'eng college','2004','cse', 'it','csit');

 >>> tup2 = (1,2,3,4,5,6,7);


21
PYTHON PROGRAMMING III YEAR/II SEM MRCET
 >>> print(tup1[0])

 mrcet

 >>> print(tup2[1:4])

 (2, 3, 4)

Tuple 1 includes list of information of mrcet

Tuple 2 includes list of numbers in it

22
PYTHON PROGRAMMING III YEAR/II SEM MRCET
We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4

Run the above code- It gives name mrcet for first tuple while for second tuple it gives
number (2, 3, 4)

Tuple as return values:

A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are
immutable.

# A Python program to return multiple values from a method using tuple

# This function returns a tuple


def fun():
str = "mrcet college"
x = 20
return str, x; # Return tuple, we could also
# write (str, x)
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/tupretval.py
mrcet college
20

 Functions can return tuples as return

values. def circleInfo(r):


""" Return (circumference, area) of a circle of radius r """
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))

23
PYTHON PROGRAMMING III YEAR/II SEM MRCET

def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)
Set:
set is an unordered collection of unique elements. It is defined using curly braces {} and each
element is separated by a comma.

set type has the following characteristics:

 Sets are unordered.


 Set elements are unique. Duplicate elements are not allowed.
 A set itself may be modified, but the elements contained in the set must be of
an immutable type.

Creating a set
my_set = {1, 2, 3, 4, 5}

Creating a set using set() function


s1 = set([1, 2, 3, 4])
print(s1) # {1, 2, 3, 4}

A set can store heterogeneous elements, i.e., a mixture of different data types such as strings, integers,
booleans, etc1. However, a set cannot store mutable elements such as lists, dictionaries, or other sets1. For
example:

# Creating a set with heterogeneous elements


s3 = {"a", 10, True, (1, 2)}
print(s3) # {(1, 2), True, 'a', 10}

# Trying to create a set with mutable elements


s4 = {[1, 2], {"a": 1}, {3, 4}}
print(s4) # TypeError: unhashable type: 'list'

An empty set is in a Boolean context:

Python
>>> x = set()
>>> bool(x)
False
24
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x or 1

A set of integers
int_set = {10, 20, 30, 40, 50}

# A set of mixed data types


mixed_set = {9, "This is a set element", (1, 2)}

# All set elements are unique


my_set = {1, 2, 3, 1, 3, 3}
print(my_set) # Output: {1, 2, 3}

# A set can be made from a list


my_set = set([1, 2, 3, 2, 4, 5, 5])
print(my_set) # Output: {1, 2, 3, 4, 5}

Basic operations in Sets


Add Items to a Set in Python
You can add an item to a set in Python by using the add() method
with the new item to be added passed in as a parameter.
Here's an example:

nameSet = {"John", "Jane", "Doe"}

nameSet.add("Ihechikara")

print(nameSet)
# {'John', 'Ihechikara', 'Doe', 'Jane'}

Modifying a Set in Python


Indexing and slicing cannot be used to access or update an element of a set. The
set data type does not support it since sets are not ordered.

The add() method is used to add a single element, and the update() method is used
to update multiple components.

25
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Removing Elements From a Set


The methods discard() and remove() are used to delete a specific item from a set.
They are identical with only one difference. The discard() method leaves the set
unmodified If the element is not present in the set. The remove() method, on the
other hand, throws an error if the element is not present in the set.
# Initialize a set
my_set = {10, 20, 30, 40, 50}
print(my_set)

# Discard an element
my_set.discard(40)
print(my_set) # Output: {10, 20, 30, 50}

# Remove an element
my_set.remove(60) # KeyError!

method to remove and return an item. However, there is no way to know


pop()
which item will be popped because the set is an unordered data type. It's
absolutely random!
# Initialize a set
my_set = set("LearnPython")

# Pop an element
print(my_set.pop())

clear() method is used to delete all elements from a set.


# Clear the set
# Initialize a set
my_set = set("LearnPython")

my_set.clear()
print(my_set) # Output: set()

Python Set copy() Method


The copy() method copies the set.
set.copy()
fruits = {"apple", "banana", "cherry"}

x = fruits.copy()

print(x)
26
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Dictionaries:

A dictionary is a collection which is unordered, changeable and indexed. In Python


dictionaries are written with curly brackets, and they have keys and values.
 Key-value pairs
 Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)

Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}

Characteristics
1. Dictionaries are Unordered : The dictionary elements key-value pairs are not
in ordered form.
2. Dictionary Keys are Case Sensitive : The same key name but with different
case are treated as different keys in Python dictionaries.

Dictionary Items - Data Types


The values in dictionary items can be of any data type:

Example
String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

27
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value. Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']

Methods:

Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.

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.
Python3
my_dict = {'1': 'Geeks', '2': 'For', '3': 'Geeks'}
my_dict.clear()
print(my_dict)

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.
Python3
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(d.get('Name'))
print(d.get('Gender'))

28
PYTHON PROGRAMMING III YEAR/II SEM MRCET

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.
Python3
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.items())[1][0])
print(list(d.items())[1][1])

Dictionary keys() Method

The keys() method in Python returns a view object with dictionary


keys, allowing efficient access and iteration.
Python3
d = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
print(list(d.keys()))

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.
Python3
d1 = {'Name': 'Ram', 'Age': '19', 'Country': 'India'}
d2 = {'Name': 'Neha', 'Age': '22'}

d1.update(d2)
print(d1)

29
PYTHON PROGRAMMING III YEAR/II SEM MRCET

dictionary operations:
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x

To access keys and values and items of dictionary:


>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1.keys()
dict_keys(['brand', 'model', 'year'])
>>> dict1.values()
dict_values(['mrcet', 'college', 2004])
>>> dict1.items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])

>>> for items in dict1.values():


print(items)
>>> for items in dict1.keys():
print(items)
brand
model
year

>>> for i in dict1.items():


print(i)
('brand', 'mrcet')
('model', 'college')
('year', 2004)

 Add/change
 Remove
 Length
 Delete

Add/change values: You can change the value of a specific item by referring to its key
name

>>> dict1 = {"brand":"mrcet","model":"college","year":2004}


>>> dict1["year"]=2005
>>> dict1
30
PYTHON PROGRAMMING III YEAR/II SEM MRCET
{'brand': 'mrcet', 'model': 'college', 'year': 2005}
Updating Dictionary

You can update a dictionary by adding a new entry or a key-value pair, modifying
an existing entry, or deleting an existing entry as shown below in the simple
example −

Live Demo

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

Remove Dictionary Items

We use the del statement to remove an element from the dictionary. For example,
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Naples"
}

# delete item having "United States" key


del country_capitals["United States"]

print(country_capitals)
Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.

To explicitly remove an entire dictionary, just use the del statement. Following is
a simple example −
Live Demo

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
31
PYTHON PROGRAMMING III YEAR/II SEM MRCET
del dict ; # delete entire dictionary

print "dict['Age']: ", dict['Age']


print "dict['School']: ", dict['School']

Python Dictionary Length

We can get the size of a dictionary by using the len() function.


country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}

# get dictionary's length


print(len(country_capitals))

What is Nested Dictionary in Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It's a collection of


dictionaries into one single dictionary. Here, the nested_dict is a nested dictionary with the
dictionary dictA and dictB . They are two dictionary each having own key and value.

Create a Nested Dictionary

We're going to create dictionary of people within a dictionary.

Example 1: How to create a nested dictionary


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(people)

Access elements of a Nested Dictionary

To access element of a nested dictionary, we use indexing [] syntax in Python.

32
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example 2: Access the elements using the [] syntax
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])

Add element to a Nested Dictionary

Example 3: How to change or add elements in a nested dictionary?


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

people[3] = {}

people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'

print(people[3])

Add another dictionary to the nested dictionary


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'}}

people[4] = {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}


print(people[4])

Delete elements from a Nested Dictionary

In Python, we use “ del “ statement to delete elements from nested dictionary.

Example 5: How to delete elements from a nested dictionary?


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
33
PYTHON PROGRAMMING III YEAR/II SEM MRCET
4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}

del people[3]['married']
del people[4]['married']

print(people[3])
print(people[4])

How to delete dictionary from a nested dictionary?


people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}

del people[3], people[4]


print(people)

Iterating Through a Nested Dictionary

Using the for loops, we can iterate through each elements in a nested dictionary.

Example 7: How to iterate through a Nested dictionary?


people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},
2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

for p_id, p_info in people.items():


print("\nPerson ID:", p_id)

for key in p_info:


print(key + ':', p_info[key])

When we run above program, it will output:

Person ID: 1
Name: John
Age: 27
Sex: Male

Person ID: 2
Name: Marie
34
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Age: 22
Sex: Female
In the above program, the first loop returns all the keys in the nested dictionary people . It
consist of the IDs p_id of each person. We use these IDs to unpack the information p_info of
each person.
The second loop goes through the information of each person. Then, it returns all of the
keys name , age , sex of each person's dictionary.
Now, we print the key of the person’s information and the value for that key.

35

You might also like