You are on page 1of 96

Subject : Programming Semester:

and problem solving I

Chapter 09:Structured Types,


Mutability and Higher-Order Functions

Faculty: Komal Waykole


1
Strings

Faculty: Komal Waykole


2
Strings : operations
• Following are the operations performed on
strings:
• Indexing
• Slicing
• Iteration
• Length of string
• Modify (uppercase,lowercase,replace,split)
• Membership operator
• Concatenate

Faculty: Komal Waykole


3
Strings : index Operation
⚫The index() method finds the first occurrence of the
specified value.
⚫The index() method raises an exception if the value is not
found.
⚫The index() method is almost the same as
the find() method, the only difference is that
the find() method returns -1 if the value is not found.
⚫Syntax: string.index(value, start, end)

Faculty: Komal Waykole


4
Strings : Index operation
⚫Example: the first occurrence of the letter "e“
OUTPUT:
1

⚫Example: The first occurrence of the letter "e"


when you only search between position 5 and 10?:
⚫ OUTPUT
⚫ 8

Faculty: Komal Waykole


5
Strings : Slicing operation
⚫You can return a range of characters by using
the slice syntax.
⚫Specify the start index and the end index,
separated by a colon, to return a part of the
string.
⚫Example: Get the characters from position 2 to position 5
⚫ OUTPUT:
⚫ llo

Faculty: Komal Waykole


6
Strings : Iteratoin
⚫ Strings are arrays, we can loop through the
characters in a string, with a for loop.
⚫ Example:
OUTPUT:

Faculty: Komal Waykole


7
Strings : length of string
⚫To get the length of a string, use
the len() function.
⚫Example:
OUTPUT:
13

Faculty: Komal Waykole


8
Strings : Modifying a string
⚫ Uppercase: The upper() method returns the
string in upper case
⚫ Example
OUTPUT:
⚫ HELLO, WORLD!

⚫ Lowercase: The lower() method returns the


string in lower case.
⚫ Example:
OUTPUT:
⚫ hello, world!
Faculty: Komal Waykole
9
Strings : Modifying a string…
⚫ Replace String: The replace() method replaces a
string with another string.
⚫ Example:
OUTPUT:
⚫ Jello, World!

⚫ Split String: The split() method returns a list where


the text between the specified separator becomes
the list items.
⚫ Example: OUTPUT:
⚫ ['Hello', ' World!']

Faculty: Komal Waykole


10
Strings : methods
Method Description
capitalize() Converts the first character to upper case
count() Returns the number of times a specified value occurs in a string

find() Searches the string for a specified value and returns the position of
where it was found
index() Searches the string for a specified value and returns the position of
where it was found
join() Converts the elements of an iterable into a string

lower() Converts a string into lower case


split() Splits the string at the specified separator, and returns a list
upper() Converts a string into upper case
title() Converts the first character of each word to upper case
Faculty: Komal Waykole 11
Strings : Operator for string

Faculty: Komal Waykole 12


Strings : concatenation operation
⚫ To concatenate, or combine, two strings you
can use the + operator.
⚫ Example:
OUTPUT:
⚫ Hello World

Faculty: Komal Waykole


13
Strings : membership operator
⚫To check if a certain phrase or character is present
in a string, we can use the keyword in.
⚫Example: OUTPUT:
True

⚫Example: OUTPUT:
True

Faculty: Komal Waykole


14
Arrays

Faculty: Komal Waykole


15
Arrays: introduction
• An array is a special variable, which can hold more
than one value at a time.
• If you have a list of items (a list of car names, for
example), storing the cars in single variables could
look like this:
• Example:

• An array can hold many values under a single


name, and you can access the values by referring
to an index number.

Faculty: Komal Waykole


16
Arrays: Access the Elements of an Array

⚫ two ways to access arrays in python :


⚫Import array package
⚫Import NumPy package

Faculty: Komal Waykole


17
Arrays: introduction to Numpy
⚫NumPy is a Python library used for working with
arrays.
⚫It also has functions for working in domain of linear
algebra, fourier transform, and matrices.
⚫NumPy stands for Numerical Python.
⚫NumPy aims to provide an array object that is up to
50x faster than traditional Python lists.
⚫The array object in NumPy is called ndarray, it
provides a lot of supporting functions that make
working with ndarray very easy.
⚫Arrays are very frequently used in data science,
where speed and resources are very important.

Faculty: Komal Waykole


18
Arrays: Why Numpy faster then list?
⚫NumPy arrays are stored at one continuous
place in memory unlike lists, so processes can
access and manipulate them very efficiently.
⚫This behaviour is called locality of reference in
computer science.
⚫This is the main reason why NumPy is faster than
lists. Also it is optimized to work with latest CPU
architectures.

Faculty: Komal Waykole


19
Arrays: Importing NumPy as np
⚫ NumPy is usually imported under the np alias.
⚫ the NumPy package can be referred to

as np instead of numpy.
⚫ Example

• OUTPUT:

Faculty: Komal Waykole


20
Arrays: NumPy

NumPy
Package

Ndarray
(one object
of NumPy
package)

Array() in
ndarray
Faculty: Komal Waykole
21
Arrays: Creating NumPy ndarray object
⚫NumPy is used to work with arrays. The array object in NumPy
is called ndarray.
⚫We can create a NumPy ndarray object by using
the array() function.
⚫type(): This built-in Python function tells us the type of the
object passed to it. Like in above code it shows
that arr is numpy.ndarray type.
⚫Example OUTPUT:

Faculty: Komal Waykole


22
Arrays: Creating NumPy ndarray object
⚫To create an ndarray, we can pass a list, tuple or any
array-like object into the array() method, and it will
be converted into an ndarray:
⚫Example OUTPUT:

⚫Example OUTPUT:

A tuple is passed
to the array()

Faculty: Komal Waykole


23
Arrays: Dimensions of an array
⚫ Dimension in arrays is one level of array depth
(nested arrays).
⚫nested array: are arrays that have arrays as
their elements.
⚫Dimensiona of array:
⚫0-D Arrays
⚫1-D Arrays
⚫2-D Arrays
⚫3-D arrays

Faculty: Komal Waykole


24
Arrays: 0-D Arrays
⚫0-D arrays, or Scalars, are the elements in an
array. Each value in an array is a 0-D array.
⚫Example: Create a 0-D array with value 42

⚫ OUTPUT:
⚫ 42

Faculty: Komal Waykole


25
Arrays: 1-D Arrays
⚫An array that has 0-D arrays as its elements is
called uni-dimensional or 1-D array.
⚫These are the most common and basic arrays.
⚫Example
⚫Example: Create a 1-D array containing the values
1,2,3,4,5:

⚫ OUTPUT:
⚫ [1 2 3 4 5]

Faculty: Komal Waykole


26
Arrays: 2-D Arrays
⚫An array that has 1-D arrays as its elements is
called a 2-D array.
⚫These are often used to represent matrix or 2nd
order tensors.
⚫NumPy has a whole sub module dedicated
towards matrix operations called numpy.mat
⚫Example: Create a 2-D array containing two arrays with
the values 1,2,3 and 4,5,6:
OUTPUT:
⚫ [[1 2 3] [4 5 6]]

Faculty: Komal Waykole


27
Arrays: 3-D Arrays
⚫An array that has 2-D arrays (matrices) as its
elements is called 3-D array.
⚫These are often used to represent a 3rd order
tensor.
⚫Example: Create a 3-D array with two 2-D arrays, both
containing two arrays with the values 1,2,3 and 4,5,6:

⚫OUTPUT:

Faculty: Komal Waykole


28
Arrays: Check dimension of Array
⚫NumPy Arrays provides the ndim attribute that
returns an integer that tells us how many
dimensions the array have.
⚫Example: OUTPUT:

Faculty: Komal Waykole


29
Arrays: Operation on array

⚫Indexing
⚫Slicing
⚫Iterating
⚫Search
⚫Sort
⚫Matrix multiplication

Faculty: Komal Waykole


30
Arrays: Indexing NumPy ndarray object
⚫Access Array Elements
⚫Array indexing is the same as accessing an array
element.
⚫You can access an array element by referring to
its index number.
⚫The indexes in NumPy arrays start with 0,
meaning that the first element has index 0, and
the second has index 1 etc.

Faculty: Komal Waykole


31
Arrays: Indexing NumPy ndarray object…
⚫Example: Get third and fourth elements from the
following array and add them.
⚫ OUTPUT:
⚫ 7

⚫Example: Accesing 2-D array


OUTPUT:

⚫ 2nd element
on
1st dim: 2

Faculty: Komal Waykole


32
Arrays: Indexing NumPy ndarray object…
⚫To access elements from 3-D arrays we can use
comma separated integers representing the
dimensions and the index of the element.
⚫Example:

⚫OUTPUT: 6

Faculty: Komal Waykole


33
Arrays: Indexing NumPy ndarray object…
⚫Negative indexing
⚫Use negative indexing to access an array from
the end.
⚫Example : Print the last element from the 2nd dim:

⚫OUTPUT:
Last element from 2nd dim: 9

Faculty: Komal Waykole


34
Arrays: Slicing
⚫Slicing in python means taking elements from
one given index to another given index.
⚫We pass slice instead of index like
this: [start:end].
⚫We can also define the step, like
this: [start:end:step].
⚫If we don't pass start its considered 0.
⚫If we don't pass end its considered length of
array in that dimension.
⚫If we don't pass step its considered 1.

Faculty: Komal Waykole


35
Arrays: Slicing…
⚫Example: Slice elements from index 4 to the end of the
array:
⚫ OUTPUT:
⚫ [5 6 7]

⚫Example: Slice elements from the beginning to index 4


⚫ OUTPUT:

[1 2 3 4]

Faculty: Komal Waykole


36
Arrays: Slicing…
⚫Negative Slicing
⚫Use the minus operator to refer to an index from the
end:
⚫Example: Slice from the index 3 from the end to index 1
from the end:
OUTPUT:
⚫ [5 6]

⚫STEP
⚫Use the step value to determine the step of the slicing:
⚫ OUTPUT:
⚫ [ 2 4]

Faculty: Komal Waykole


37
Arrays: Slicing…
⚫Example: Slicing 2-D array OUTPUT:
⚫ [7 8 9]

⚫Example: OUTPUT:

Faculty: Komal Waykole


38
Arrays: Slicing…
⚫Example: From both elements, slice index 1 to index
4 (not included), this will return a 2-D array:

⚫OUTPUT:

Faculty: Komal Waykole


39
Arrays: Iterating through arrays
⚫Iterating means going through elements one by
one.
⚫As we deal with multi-dimensional arrays in
numpy, we can do this using basic for loop of
python.
⚫Example: Iterate on the elements of the following 2-D
array:
⚫ OUTPUT:
⚫ [1 2 3]
[4 5 6]

Faculty: Komal Waykole


40
Arrays: Iterating through arrays…
⚫Example: Iterate on each scalar element of the 2-D array:
⚫ OUTPUT:

⚫Example:

Faculty: Komal Waykole


41
Arrays: Searching Arrays
⚫Searching trough an array for a certain value, and
return the indexes that get a match.
⚫To search an array, use the where() method.
⚫Example: OUTPUT:
⚫ ( array ([3, 5, 6]), )

⚫The example above will return a tuple(tuple is ordered


and unchangeable.): (array([3, 5, 6],)
⚫Which means that the value 4 is present at index 3, 5, and 6.

Faculty: Komal Waykole


42
Arrays: Sorting Arrays
⚫Sorting means putting elements in an ordered
sequence.
⚫Ordered sequence is any sequence that has an
order corresponding to elements, like numeric or
alphabetical, ascending or descending.
⚫The NumPy ndarray object has a function
called sort(), that will sort a specified array.
⚫You can also sort arrays of strings, or any other
data type

Faculty: Komal Waykole


43
Arrays: Sorting Arrays…
⚫Example OUTPUT:
['apple'
'banana'
'cherry']

⚫Example: Sort 2-D arrays


OUTPUT:
⚫ [[2 3 4] [0 1 5]]

Faculty: Komal Waykole


44
Arrays: matrix multiplication…
⚫Matrix multiplication: matrix1(2*3)* matrix2(3*2)
= result(2*2)

Faculty: Komal Waykole


45
Arrays: matrix multiplication…
⚫To multiply two matrices, we use dot() method.
⚫Example: OUTPUT:

⚫* is used for array multiplication (multiplication


of corresponding elements of two arrays) not
matrix multiplication.

Faculty: Komal Waykole


46
Lists
and
its mutability

Faculty: Komal Waykole


47
Lists
• The list is a most versatile datatype available in
Python which can be written as a list of
comma-separated values (items) between
square brackets.
• Important thing about a list is that items in a
list need not be of the same type.
• Create List
⚫Example:
a=[‘AAA’,’BBB’,’CCC’]
b=[10,20,30,40]
Here a and b are the lists data structures.

Faculty: Komal Waykole


48
Lists: Accessing Values in List
⚫Accessing Values in List
⚫Individual element of the list can be accessed
using index of the list.
⚫For example
rollNo = [1,2,3,4,5]
name=['Shilpa','Chinmaya','Akash','Aditya','Swati']
print(rollNo[0],name[0])
O/P: 1 Shilpa
print(rollNo[1],name[1])
O/P: 2 Chinmaya
print(rollNo[1:4])
O/P: [2, 3, 4]

Faculty: Komal Waykole


49
Lists: Deleting Values in List
⚫Deleting Values in List
⚫The deletion of any element from the list is
carried out using various functions like
⚫ pop,
⚫remove,
⚫del.

Faculty: Komal Waykole


50
Lists: Deleting Values in List
⚫pop Function :
⚫If we know the index of the element to be deleted
then just pass that index as an argument to pop
function.
⚫example
a=['u','v','w','x','y','z']
val=a.pop(1) #the element at index 1 is v, it is deleted
o/p: a ['u', 'w', 'x', 'y', 'z'] #list after deletion
val #deleted element is present in variable val
o/p: 'v'
⚫If we do not provide any argument to the pop function then
the last element of the list will be deleted.

Faculty: Komal Waykole


51
Lists: Deleting Values in List
⚫Remove function :
⚫If we know the value of the element to be deleted then
the remove function is used.
⚫That means the parameter passed to the remove
function is the actual value that is to be removed from
the list.
⚫Unlike, pop function the remove function does not
return any value.
⚫The execution of remove function is shown by
following illustration
⚫Example:-
a=['a','b','c','d','e']
a.remove('c')
Output: a ['a', 'b', 'd', 'e']
Faculty: Komal Waykole
52
Lists: Deleting Values in List
⚫Delete function
⚫In python, it is possible to remove more than one
element at a time using del function.
⚫example
a=['a','b','c','d','e']
del a[2:4]
Output:
a ['a', 'b', 'e']

Faculty: Komal Waykole


53
Lists: Updating Values in List
⚫Updating List
⚫ Lists are mutable. That means it is possible to
change the values of list.
⚫If the bracket operator is present on the left hand
side, then that element is identified and the list
element is modified accordingly.
⚫Example:
a=['AAA','BBB','CCC']
a[1]='XXX'
Print(a)
Output:
a ['AAA', 'XXX', 'CCC']
Faculty: Komal Waykole
54
Lists: Slicing Values in List
⚫The : Operator used within the square bracket
that it is a list slice and not the index of the list.
⚫Example:
a=[10,20,30,40,50,60]
a[1:4]
OUTPUT:
[20, 30, 40]

Faculty: Komal Waykole


55
Lists: operators used in list
operator example result

Concatenation( Concatenate two list items and [1, 2, 3, 4, 5, 6]


+) results in a single list .
EG: [1, 2, 3] + [4, 5, 6]
Repetition(*) It repeats the text for given ['Hi!', 'Hi!', 'Hi!']
number of times.
EG: ['Hi!'] * 3
Membership Checks an item is present in the True
(in, not in) list or not.Returns “TRUE” if
present,”FALSE” if absent.
EG: 3 in [1, 2, 3]

Faculty: Komal Waykole


56
Lists: Functions performed on list
(manipulating the list)
function example result

Iteration It will visit and print each value present 1 2 3


(traverse) in the list.
EG: for x in [1, 2, 3]: print x,
range() we can access each element of the list using [10,20,30,40]
index of a list.
EG: >a=[10,20,30,40]
for i in range(len(a)):
print a
Len() The len() function is used to find the number of 4
elements present in the list.
EG: a=[10,20,30,40]
Print(len(a))

Faculty: Komal Waykole


57
Lists: Functions performed on list
(manipulating the list)…
function example result

Max() returns the elements from the list with 700


maximum value.
EG: list1 = [ [456, 700, 200]
print (max(list1))
Min() Returns the elements from the list with 200
minimum value.
EG: list1 = [ [456, 700, 200]
print (min(list1))
List() It takes sequence types and converts them to [123, 'xyz',
lists. This is used to convert a given tuple into 'zara', 'abc']
list.
EG: aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print (aList)
Faculty: Komal Waykole
58
Lists:Methods performed on list
(manipulating the list)…
method description Syntax
append() Add a single element to the end of the list.append(item)
list. doesn't return any value
extend() adds iterable elements(multiple) to the list.extend(iterable)
end of the list. modifies the original list.
It doesn't return any value. It can takes
an iterable such as list, tuple, string etc.

count() returns count of the element in the list. list.count(element)

index() returns the index of the element in the list.index(element, start,


list. end)
element - the element to be searched
start - start searching from this index
end - search the element up to this index

Faculty: Komal Waykole


59
Lists:Methods performed on list
(manipulating the list)…
method description Syntax

sort() sorts elements of a list. list.sort(key=...,


reverse - If True, the sorted list is reverse=...
reversed (or sorted in Descending
order)
key - function that serves as a key
for the sort comparison
insert() insert an element to the list. doesn't list.insert(i, ele)
return anything; It only updates the i=index
current list. Ele=element

Faculty: Komal Waykole


60
Lists:Methods performed on list
(manipulating the list)…
• Example: to Append and element
currencies = ['Dollar', 'Euro', 'Pound’]
# append 'Yen' to the list
currencies.append('Yen')
print(currencies)
# Output: ['Dollar', 'Euro', 'Pound', 'Yen']

Faculty: Komal Waykole


61
Lists:Methods performed on list
(manipulating the list)…
• Example: to Extend an element
# create a list
prime_numbers = [2, 3, 5]
# create another list
numbers = [1, 4]

# add all elements of prime_numbers to numbers


numbers.extend(prime_numbers)

print('List after extend():', numbers)

# Output: List after extend(): [1, 4, 2, 3, 5]

Faculty: Komal Waykole


62
Lists:Methods performed on list
(manipulating the list)…
• Example: to count an element
# create a list
numbers = [2, 3, 5, 2, 11, 2, 7]
# check the count of 2
count = numbers.count(2)
print(count)

# Output: 3

Faculty: Komal Waykole


63
Lists:Methods performed on list
(manipulating the list)…
• Example: to index an element

animals = ['cat', 'dog', 'rabbit', 'horse’]


# get the index of 'dog'
index = animals.index('dog')
print(index)
# Output: 1

Faculty: Komal Waykole


64
Lists:Methods performed on list
(manipulating the list)…
• Example: to sort list element

prime_numbers = [11, 3, 7, 5, 2]
# sort the list
prime_numbers.sort()
print(prime_numbers)

# Output: [2, 3, 5, 7, 11]

Faculty: Komal Waykole


65
Lists:Methods performed on list
(manipulating the list)…
• Example: to insert an element
# create a list of vowels
vowel = ['a', 'e', 'i', 'u’]
# 'o' is inserted at index 3 (4th position)
vowel.insert(3, 'o')
print('List:', vowel)

# Output: List: ['a', 'e', 'i', 'o', 'u']

Faculty: Komal Waykole


66
Lists: Comprehension
• List comprehension is an elegant and concise way to
create a new list from an existing list in Python.
• A list comprehension consists of an expression
followed by for statement inside square brackets.
• Example
pow2 = [2 ** x for x in range(10)]
print(pow2)
• Output
[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

Faculty: Komal Waykole


67
Tuples: Creating a Tuple
• A tuple is created by placing all the items (elements) inside
parentheses (), separated by commas.
• The parentheses are optional, however, it is a good practice
to use them.
• A tuple can have any number of items and they may be of
different types (integer, float, list, string, etc.).
• Example:
#tuple with mixed datatypes
my_tuple = (1, "Hello", 3.4)
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

Faculty: Komal Waykole


68
Tuples: Access Tuple Elements
• Various ways in which we can access the elements of a
tuple.
1. Indexing
2. Negative Indexing.
3. Slicing.

Faculty: Komal Waykole


69
Tuples: Access Tuple Elements-indexing
• Example: accessing tuples
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
• Example: accessing nested tuples
n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
# nested index
print(n_tuple[0][3]) # 's'
print(n_tuple[1][1]) #4

Faculty: Komal Waykole


70
Tuples: Access Tuple Elements-Negative
indexing

• Example: Negative indexing for accessing tuple


elements
my_tuple = ('p', 'e', 'r', 'm', 'i', 't')
print(my_tuple[-6])
# Output: 'p'

Faculty: Komal Waykole


71
Tuples: Access Tuple Elements-Slicing
• Example:
my_tuple = ('p','r','o','g','r','a','m’)
# elements 2nd to 4th
print(my_tuple[1:4])
# Output: ('r', 'o', 'g')

Faculty: Komal Waykole


72
Tuples: Changing a Tuple
• Elements of a tuple cannot be changed once they have
been assigned.
• But, if the element is itself a mutable data type like a list, its
nested items can be changed.
• We can also assign a tuple to different values.
• Example: Changing tuple values
my_tuple = (4, 2, 3, [6, 5])
my_tuple[1] = 9
# However, item of mutable element can be changed
my_tuple[3][0] = 9
print(my_tuple)
# Output: (4, 2, 3, [9, 5])

Faculty: Komal Waykole


73
Tuples: Deleting a Tuple
• Deleting a tuple entirely, however, is possible using the
keyword del.
• Example: Deleting tuples
my_tuple = ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z’)
del my_tuple
print(my_tuple)
OUTPUT:
NameError: name 'my_tuple' is not defined

Faculty: Komal Waykole


74
Tuples: Operators used
• Example: concatenation(+) and repetition(*)

print((1, 2, 3) + (4, 5, 6))


Output: (1, 2, 3, 4, 5, 6)

# Repeat
print(("Repeat",) * 3)
Output: ('Repeat', 'Repeat', 'Repeat')

Faculty: Komal Waykole


75
Tuples: Operators used
• Membership means checking if the element is
present in the tuple or not.
• The membership operation is performed using in
operator.
• Example:
t1=(10,20,30,40,50)
print(3 in t1) OUTPUT: False
print(30 in t1) OUTPUT: True

Faculty: Komal Waykole


76
Tuples: Methods used

Example:
my_tuple = ('a', 'p', 'p', 'l', 'e',)
print(my_tuple.count('p')) # Output: 2
print(my_tuple.index('l')) # Output: 3

Faculty: Komal Waykole


77
Tuple: Sorting

Faculty: Komal Waykole


78
Tuple: built in functions of tuples

Faculty: Komal Waykole 79


Tuple: Sorting…

Faculty: Komal Waykole


80
Tuples: Advantages of tuple over list
• Datatype:
• tuples use heterogeneous (different) data types and
lists for homogeneous (similar) data types.
• Performance:
• tuples are immutable, iterating through a tuple is
faster than with list. So there is a slight performance
boost.
• Transforming to dictionary:
• Tuples that contain immutable elements can be used
as a key for a dictionary. With lists, this is not possible.
• Protection:
• If you have data that doesn't change, implementing it
as tuple will guarantee that it remains write-protected.

Faculty: Komal Waykole


81
Tuples: program
Example: A python program to sort a tuple with nested
tuples.
emp = ((100, "Varun", 9000.90),
(20, "Nihaarika", 5500.75), (30, "Vanaja",8900.00),
(40, "Karthik", 5000.50)) # tuple having nested tuples for
emp data having ID, name, salary
print(sorted(emp))

Output:
[(20, 'Nihaarika', 5500.75),
(30, 'Vanaja', 8900.0),
(40, 'Karthik', 5000.5),
(100, 'Varun', 9000.9)]

82
Faculty: Komal Waykole
Dictionary:
• Python dictionary is an unordered collection of
items. Each item of a dictionary has a key/value
pair.
• Dictionaries are optimized to retrieve values
when the key is known.

83
Faculty: Komal Waykole
Dictionary: Creating Dictionary
• Creating a dictionary is as simple as placing
items inside curly braces {} separated by
commas.
• An item has a key and a corresponding value that
is expressed as a pair (key: value).
• While the values can be of any data type and can
repeat, keys must be of immutable type (string,
number or tuple with immutable elements) and
must be unique.
• Example:
# using dict()
my_dict = dict({1:'apple', 2:'ball'})

84
Faculty: Komal Waykole
Dictionary: Accessing Dictionary
• Indexing:
⚫ While indexing is used with other data types to
access values, a dictionary uses keys. Keys can be
used either inside square brackets [ ] or with the
get() method.
⚫ If we use the square brackets [ ], KeyError is
raised in case a key is not found in the dictionary.
On the other hand, the get() method returns None
if the key is not found.
⚫ Example:

my_dict = {'name': 'Jack', 'age': 26}


print(my_dict.get('age’))
Output: 26

85
Faculty: Komal Waykole
Dictionary: Changing values
• Example: update value
my_dict = {'name': 'Jack', 'age': 26}
my_dict['age'] = 27
print(my_dict)
Output: {'age': 27, 'name': 'Jack’}
• Example: Adding value
my_dict = {'name': 'Jack', 'age': 26}
my_dict['address'] = 'Downtown'
print(my_dict)
Output: {'address': 'Downtown', 'age': 27, 'name':
'Jack'}

86
Dictionary: deleting values
• pop() method. This method removes an item
with the provided key and returns the value.
• The popitem() method can be used to remove
and return an arbitrary (key, value) item pair from
the dictionary.
• All the items can be removed at once, using the
clear() method.
• We can also use the del keyword to remove
individual items or the entire dictionary itself.

87
Dictionary: deleting values
• Example:
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares.pop(4)) # Output: 16
squares.clear() # remove all items
del squares #deletes entire dictionary

88
Dictionary: iteration
• Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
OUTPUT:
1
9
25
49
81

89
Dictionary: membership operator
• if a key is in a dictionary or not using the
keyword in. the membership test is only for the
keys and not for the values.
• Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(1 in squares)
print(2 not in squares)
OUTPUT:
True
true

90
Dictionary: Built in functions

91
Dictionary: Built in functions
• Example:
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(all(squares))
print(any(squares))
print(len(squares))
print(sorted(squares))
OUTPUT:
False
True
6
[0, 1, 3, 5, 7, 9]
92
Dictionary: methods used
Method Description

clear() Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.


Return a new object of the dictionary's items in (key, value)
items()
format.

keys() Returns a new object of the dictionary's keys.

update([ Updates the dictionary with the key/value pairs from other,
other]) overwriting existing keys.

values() Returns a new object of the dictionary's values

93
Dictionary: Converting lists to dictionary
• There are two steps involved to convert the lists
into a dictionary.
1. The first step is to create a 'zip' class object by
passing the two lists to zip() function as:
z = zip(countries, cities)
⚫ The zip() function is useful to convert the
sequences into a zip class object.
2. The second step is to convert the zip object into
a dictionary by using dict() function.
d = dict(z)

94
Dictionary:
Convert two list into dictionary
countries = ["USA", "India", "Germany", "France"]
cities = ['Washington', 'New Delhi', 'Berlin', 'Paris']
z = zip(countries, cities)
d = dict(z)
print('{:15s} -- {:15s}'.format('COUNTRY', 'CAPITAL'))
for k in d:
print('{:15s} -- {:15s}'.format(k, d[k]))

95
Important questions
1. Difference between find() and index() in python string.
2. Write a python program to change the case of string to
uppercase and lowercase.
3. Write a python program to replace string” jungle” with
“forest” in string “welcome to the jungle”.
4. Write short note on numpy
5. With example explain any 4 functions used with
list/tuple/string/array.
6. Difference between extend() and append() in list.
7. What is list comprehension.
8. Write short note on dimensions of array.
9. Write the use of ndim()
10. Write methods used by dictionaries.
11. Write short note on sort() for list and arrays
12. Advantages of tuples over list.

Faculty: Komal Waykole


96

You might also like