You are on page 1of 36

[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

UNIT IV LISTS, TUPLES, DICTIONARIES


Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations and
methods; advanced list processing - list comprehension; Illustrative programs: selection sort,
insertion sort, mergesort, histogram.

4.1 LISTS
 A list is an ordered set of values (any type), where each value is identified by an index.
 It can be created as a set of values separated by commas within square brackets.
 The values in a list are called elements or items.
Example
list1=[10, 20, 30, 40]
list2=['white ‘, 'black’, 'red']
list3=[10,'white',8.4]

4.1.1 List Creation:


 There are several ways to create a new list; the simplest is to enclose the elements in
square brackets ([ and ])
 Example:
>>>t=[10, 20, 30, 40,50]
>>>t
[10,20,30,40,50]
 The elements of a list don’t have to be the same type. The following list contains a
string, a float, an integer, and  another list:
['spam', 2.0, 5]
 A list within another list is called nested list. A list that contains no elements is called
an empty list; it can be created with empty brackets, [].
 The function list creates a new list with no items.
>>>t=list()
>>>t
[]

Indexing Lists:

PPG INSTITUTE OF TECHNOLOGY Page 1


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Each item in a list corresponds to an index number, which is an integer value, starting
with the index number 0.
 Any integer expression can be used as an index.
 If you try to read or write an element that does not exist, you get an IndexError.
 If an index has a negative value, it counts backward from the end of the list.
 Example:
t=[10,20,30,40,50]

negative index -5 -4 -3 -2 -1

t 10 20 30 40 50

positive index 0 1 2 3 4
4.1.2 Accessing Items in List:
 Item of the list can be accessed by referring  its index number.
 Example:
>>>t=[10, 20, 30, 40,50]
>>>t[1]
20
4.1.3 Modifying Items in List:
 We can use indexing to change items within the list, by setting an index number equal
to a different value.
 Example:
>>>t=[10, 20, 30, 40,50]
>>>t[1]=200
>>>t
[10,200,30,40,50]
4.1.4 Removing an Item from a List:
 Items can be removed from lists by using the del statement. This will delete the value
at the specified index number within the list.
 Example:
>>>t=[10,20,30,40,50]
>>>del t[3]
>>>t
[10,20,40,50]

PPG INSTITUTE OF TECHNOLOGY Page 2


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

4.2 LIST SLICES


 A segment of a list is called a slice. Selecting a slice is similar to selecting an element:
 The operator [n:m] returns the part of the list from the “n-eth” character to the
“m-eth”
 character, including the first but excluding the last.
 Example:
 >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
 If we omit the first index (before the colon), the slice starts at the beginning of the
string.
>>> t[:4]
['a', 'b', 'c', 'd']
 If we omit the second index, the slice goes to the end of the string:
>>> t[3:]
['d', 'e', 'f']
 If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks:
>>>t=[1,2,3,4,5]
>>>t[4:3])
[]
 By default, Python sets this increment to 1, but that extra colon at the end of the
numbers allows us to specify the slicing increment.
>>>t=[1,2,3,4,5]
>>>t[::2]
[1,3,5]
 It also possible to apply negative index.
>>>t=[1,2,3,4,5]
>>>t[-3:-1]
[3,4]
 A slice operator on the left side of an assignment can update multiple elements.
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
PPG INSTITUTE OF TECHNOLOGY Page 3
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

>>> t[1:3] = ['x', 'y']


>>> t
['a', 'x', 'y', 'd', 'e', 'f']

4.3 LIST OPERATIONS


Python expression Results Description
len([1,2,3,4]) 4 Returns the number of elements
(length) in the given list.
[1,2,3,4]+[5,6] [1,2.3,4,5,6] Perform Concatenation operation
or combines two or more list with
+ operator
[‘priya’]*2 [‘priya’,’priya’] ‘*’ operator repeats a list and a
number to specify the number of
times the list to be repeated.
2 in [1,2,3] True Membership operator – returns
true if the given element is present
in the list, otherwise it returns false
for x in [1,2,3,4,5,6] 123456 Iteration - block of statements
print(x) which are repeatedly executed
until the last element in the list.

4.4 LIST METHODS


 Python provides the following built-in methods to retrieve and manipulate the data in
list.

Methods Description
append() Adds an element to the end of the list
extend() Add all contents of the second list to the first list
insert() Insert an item at the defined index
remove() Removes an item from the list
pop() Removes and returns an element at the given index
clear() Removes all items from the list
index() Returns the index of the first matched element
count() Returns the number of occurrences of an element
specified in the list
sort() Sort items in a list in an ascending order
reverse() Reverse the order of items in the list
PPG INSTITUTE OF TECHNOLOGY Page 4
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

4.4.1 append()
 Adds an element to the end of the list
 Syntax:
list.append(element)
 Example:
mylist=['cake', 'cooldrinks']
mylist.append('milk')
print('after appending')
print(mylist)
 Output:
after appending
['cake', 'cooldrinks', 'milk']

4.4.2 extend()
 Add all contents of the second list to the first list
 Syntax:
list.extend(secondlistname)

 Example:
mylist=['cake', 'cooldrinks']
newlist=['milk']
print('before extending',mylist)
mylist.extend(newlist)
print('after extending', mylist)
 Output:
before extending ['cake', 'cooldrinks']
after extending ['cake', 'cooldrinks', 'milk']
4.4.3 insert()
 Insert an item at the defined index
 Syntax:
list.insert(index,element)
 Example:
PPG INSTITUTE OF TECHNOLOGY Page 5
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

mylist=['cake', 'cooldrinks']
print('before inserting',mylist)
mylist.insert(1,'milk')
print('after inserting', mylist)
 Output:
before inserting ['cake', 'cooldrinks']
after inserting ['cake', 'milk', 'cooldrinks']
4.4.4 remove()
 Removes an item from the list
 Syntax:
list.remove(element)
 Example:
mylist=['cake', 'cooldrinks','milk','jam']
print('before removing',mylist)
mylist.remove('milk')
print('after removing', mylist)

 Output:
before removing ['cake', 'cooldrinks', 'milk', 'jam']
after removing ['cake', 'cooldrinks', 'jam']
4.4.5 pop()
 Removes and returns an element at the given index
 Syntax:
list.pop(index)
 Example:
mylist=['cake', 'cooldrinks','milk','jam']
print('before poping',mylist)
mylist.pop(2)
print('after poping', mylist)
 Output:
before poping ['cake', 'cooldrinks', 'milk', 'jam']
after poping ['cake', 'cooldrinks', 'jam']
4.4.6 clear()
PPG INSTITUTE OF TECHNOLOGY Page 6
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Removes all items from the list


 Syntax:
list.clear()
 Example:
mylist=['cake', 'cooldrinks','milk','jam']
print('before clearing',mylist)
mylist.clear()
print('after clearing', mylist)
 Output:
before clearing ['cake', 'cooldrinks', 'milk', 'jam']
after clearing []
4.4.7 index()
 Returns the index of the first matched element
 Syntax:
list.index(element)
 Example:
mylist=['cake', 'cooldrinks','milk','jam']
print(mylist.index('milk'))
 output:
2
4.4.8 count()
 Returns the number of occurrences of an element specified in the list
 Syntax:
listname.count(element)
 Example:
mylist=['cake','milk', 'cooldrinks','milk','jam']
print(mylist)
print(mylist.count('milk'))
 Output:
['cake', 'milk', 'cooldrinks', 'milk', 'jam']
2
4.4.9 sort()
 Sort items in a list in an ascending order
PPG INSTITUTE OF TECHNOLOGY Page 7
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Syntax:
listname.sort(element)
 Example:
mylist=['cake','tea', 'cooldrinks','milk','jam']
print('before sorting',mylist)
mylist.sort()
print('After sorting',mylist)
 Output:
before sorting ['cake', 'tea', 'cooldrinks', 'milk', 'jam']
After sorting ['cake', 'cooldrinks', 'jam', 'milk', 'tea']
4.4.10 reverse()
 Reverse the order of items in the list

 Syntax:
list.reverse()
 Example:
mylist=['cake','tea', 'cooldrinks','milk','jam']
print('before reversing',mylist)
mylist.reverse()
print('After reversing',mylist)
 Output:
before reversing ['cake', 'tea', 'cooldrinks', 'milk', 'jam']
After reversing ['jam', 'milk', 'cooldrinks', 'tea', 'cake']
4.4.11 Example Program for the usage of List Methods:
mylist=[10, 20]
mylist.append(30)
print('1.APPEND METHOD')
print(mylist)
newlist=[40]
print('2.EXTEND METHOD')
print('before extending',mylist)
mylist.extend(newlist)
print('after extending', mylist)
PPG INSTITUTE OF TECHNOLOGY Page 8
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print('3.INSERT METHOD')
print('before inserting',mylist)
mylist.insert(1,15)
print('after inserting', mylist)
print('4.REMOVE METHOD')
print('before removing',mylist)
mylist.remove(15)
print('after removing', mylist)
print('5.POP METHOD')
print('before poping',mylist)
mylist.pop(2)
print('after poping', mylist)
print('6.INDEX METHOD')
print('The index is at ',mylist.index(20))
print('7.COUNT METHOD')
print(mylist.count(20))
print('8.SORT METHOD')
print('before sorting',mylist)
mylist.sort()
print('After sorting',mylist)
print('9.REVERSE METHOD')
print('before reversing',mylist)
mylist.reverse()
print('After reversing',mylist)
print('10.CLEAR METHOD')
print('before clearing',mylist)
mylist.clear()
print('after clearing', mylist)
OUTPUT:
1.APPEND METHOD
[10, 20, 30]
2.EXTEND METHOD
before extending [10, 20, 30]
PPG INSTITUTE OF TECHNOLOGY Page 9
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

after extending [10, 20, 30, 40]


3.INSERT METHOD
before inserting [10, 20, 30, 40]
after inserting [10, 15, 20, 30, 40]
4.REMOVE METHOD
before removing [10, 15, 20, 30, 40]
after removing [10, 20, 30, 40]
5.POP METHOD
before poping [10, 20, 30, 40]
after poping [10, 20, 40]
6.INDEX METHOD
The index is at 1
7.COUNT METHOD
1
8.SORT METHOD
before sorting [10, 20, 40]
After sorting [10, 20, 40]
9.REVERSE METHOD
before reversing [10, 20, 40]
After reversing [40, 20, 10]
10.CLEAR METHOD
before clearing [40, 20, 10]
after clearing []

4.5 LIST LOOP


 The most common way to traverse the elements of a list is with a for loop. The syntax
is the same as for strings but it read only the elements of the list
 Example 1:
mylist=['cake','tea', 'cooldrinks','milk','jam']
for items in mylist:
print(items)
 Output:
cake
PPG INSTITUTE OF TECHNOLOGY Page 10
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

tea
cooldrinks
milk
jam

4.5.1 for items in mylist:


 The keyword “for” tells Python to get ready to use a loop.
 The variable “items” is a temporary variable and it will place each item in the list,
one at a time.
 Example 2:
numlist=[1,2,3,4,5]
for items in numlist:
print(items)
 Output:
1
2
3
4
5
 A for loop over an empty list never executes the body:
for x in []:
print 'This never happens.'
 4.5.2 Use of range and len functions:
 To access/traverse the element of a list, range and len function can be combined as
follows.
 Here n is the length of the list
 len-> returns the no. of elements in the list,
 range->returns a list of indices from 0 to n-1
 Example:
numlist=[10,20,30,40,50]
for items in range(len(numlist)):
print(numlist[items])
 Output:
PPG INSTITUTE OF TECHNOLOGY Page 11
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

10
20
30
40
50
4.6 LIST MUTABILITY
 Lists are mutable i.e., we can able to add/delete /replace any value in the list at any
time.
 The slice operator on the left side of an assignment operation can update single or
multiple elements of a list.
 New elements can be added using append() method
 The elements can be delete using pop() method
 Syntax:
mylist[index]=value
 Program:
mylist=[5,8,56,45,7,87]
print('Old list values are', mylist)
mylist[4]=70
print('New list values are',mylist)
 Output:
Old list values are [5, 8, 56, 45, 7, 87]
New list values are [5, 8, 56, 45, 70, 87]

4.7 ALIASING
 If mylist is a list object which holds data and mylist is assigned to newlist, then both
variable refer to same object.
mylist
[1,2,3]

newlist

 An object with more than one reference and one name is called aliased
 Alaised object is mutable in nature
 Example:
mylist=[1,2,3]
PPG INSTITUTE OF TECHNOLOGY Page 12
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

newlist=mylist
print('mylist values are:', mylist)
print('newlist values are:', newlist)
mylist[0]=1000
print('mylist values are:', mylist)
print('newlist values are:', newlist)
 Output:
mylist values are: [1, 2, 3]
newlist values are: [1, 2, 3]
mylist values are: [1000, 2, 3]
newlist values are: [1000, 2, 3]

mylist
[1000,2,3]
newlist

4.8 CLONING LISTS


 For mutable sequences(like lists), a copy of an existing object may required so that
one object can be changed without affecting another.
 Cloning operation can be used to create a copy of an existing list so that changes
made in one copy of the list will not affect another.
 The copy contains the same elements as the original.

oldlist
[10,20,30,40,50]
newlist

cloning

oldlist [10,20,30,40,50]

newlist [10,20,30,40,50]

PPG INSTITUTE OF TECHNOLOGY Page 13


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

4.8.1Various methods of cloning list:


Method 1:
 list() function:
Built-in list() function can be used for cloning lists
 Syntax:
newlist=list(oldlist)
 Program:
oldlist=[10,20,30,40,50]
newlist=list(oldlist)
print('The old list is',oldlist)
print('The new list is',newlist)
oldlist[0]=5
print('The old list is',oldlist)
print('The new list is',newlist)
 Output:
The old list is [10, 20, 30, 40, 50]
The new list is [10, 20, 30, 40, 50]
The old list is [5, 20, 30, 40, 50]
The new list is [10, 20, 30, 40, 50]

Method 2:
 copy.copy() function:
copy.copy() function is little slower than list() since it has to determine data
type of oldlist first
 Syntax:
newlist=copy.copy(oldlist)
 Program:
import copy
oldlist=[10,20,30,40,50]
newlist=copy.copy(oldlist)
print('The old list is',oldlist)
PPG INSTITUTE OF TECHNOLOGY Page 14
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print('The new list is',newlist)


oldlist[0]=5
print('The old list is',oldlist)
print('The new list is',newlist)
 Output:
The old list is [10, 20, 30, 40, 50]
The new list is [10, 20, 30, 40, 50]
The old list is [5, 20, 30, 40, 50]
The new list is [10, 20, 30, 40, 50]
Method 3:
 copy.deepcopy() function:
copy.deepcopy() function is slowest and memory-consuming method
 Syntax:
newlist=copy.deepcopy(oldlist)
 Program:
import copy
oldlist=[10,20,30,40,50]
newlist=copy.deepcopy(oldlist)
print('The old list is',oldlist)
print('The new list is',newlist)
oldlist[0]=5
print('The old list is',oldlist)
print('The new list is',newlist)
 Output:
The old list is [10, 20, 30, 40, 50]
The new list is [10, 20, 30, 40, 50]
The old list is [5, 20, 30, 40, 50]
The new list is [10, 20, 30, 40, 50]

4.9 LIST PARAMETERS

PPG INSTITUTE OF TECHNOLOGY Page 15


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Passing a list as an argument actually passes a reference to the list, not a copy or clone
of the list.
 When a list is passed as a parameter to a function, the function gets a reference to the
list.
 Example 1: Insert the element in the list
def insert(t): #function defintion
t.insert(1,15) #inserts the new element 15 at the index 1
mylist=[10,20,30,40,50]
print('Before calling the insert function',mylist)
insert(mylist) #function call
print('After calling the insert function',mylist)
 Output:
Before calling the insert function [10, 20, 30, 40, 50]
After calling the insert function [10, 15, 20, 30, 40, 50]
 Example 2: Creates and returns a new list
def display(t): #function defintion
return t[:]
mylist=[10,20,30,40,50]
print('mylist is:',mylist)
newlist=display(mylist) #function call
print('newlist is',newlist)
 Output:
mylist is: [10, 20, 30, 40, 50]
newlist is [10, 20, 30, 40, 50]

4.10 TUPLES
 A tuple is a sequence of immutable Python objects i.e. the tuples cannot be changed
unlike lists.
 Tuples use parentheses to represent it.

4.10.1 Creating Tuples


 Tuples can be define elements separated by comma within parenthesis

PPG INSTITUTE OF TECHNOLOGY Page 16


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Syntax:
var_name=(element1,element2,…elemntn)
 Example:
tuple=(1,2,3,4,5,6,7,8)
 The elements of a list don’t have to be the same type
tuple=(‘gold’,454,5.3,4)
 We can also create empty tuple as follows
tuple1=()
 Empty tuple can also be created using tuple() function as follows:
t=tuple()
 Creating tuple from string:
string="hello"
print('the string are', string)
mytuple=tuple(string)
print('strings converted to tuples',mytuple)
Output:
the string are hello
strings converted to tuples ('h', 'e', 'l', 'l', 'o')
 Creating tuple from list
list=['w','e','l','c','o','m','e','to','python']
print('The lists are', list)
mytuple=tuple(list)
print('list converted to tuples',mytuple)
Output:
The lists are ['w', 'e', 'l', 'c', 'o', 'm', 'e', 'to', 'python']
list converted to tuples ('w', 'e', 'l', 'c', 'o', 'm', 'e', 'to', 'python')
 Creating tuple from keyboard input:
mytuple=tuple(input('Enter tuple elements'))
print (mytuple)
Output:
Enter tuple elements 123abc
('1', '2', '3', 'a', 'b', 'c')

PPG INSTITUTE OF TECHNOLOGY Page 17


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

4.10.2 Accessing Values


 Indexing and slicing can be used to access item on tuple
4.10.2.1 Indexing
 The index operator indicates the index of the element to access.
 The 1st element of the index is zero
 Accessing an item outside the scope of the indexed elements will generate an
IndexError.
String P R O G R A M
Index 0 1 2 3 4 5 6
Negative index -7 -6 5 -4 -3 -2 -1

 Example Program:
newtuple = ('p','r','o','g','r','a','m')
print(newtuple[0]) # to accesss the 1st element
print(newtuple[6]) # to access the 7 th element
print(newtuple) # to access the original list
print(newtuple[-1]) # to access the last item in the list
 Output:
p
m
('p', 'r', 'o', 'g', 'r', 'a', 'm')
m

4.10.2.2 Slicing
 Slicing operator [: ] is used to access the range of items in the tuple.
 Syntax:
Tuplename[start:finish-1]

Where
Tuplename ->user defined name
Start->index of the initial character of the substring
Finish->index of the ending character of the substring
 Program:
newtuple = ('p','r','o','g','r','a','m')

PPG INSTITUTE OF TECHNOLOGY Page 18


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print(newtuple[2:6])
print(newtuple[2:])
print(newtuple[:4])
 Output:
('o', 'g', 'r', 'a')
('o', 'g', 'r', 'a', 'm')
('p', 'r', 'o', 'g')

4.10.2.3 Updating Tuples:


 Tuples are immutable means that the tuple values cannot be updated or changed.
 The portion of the existing tuples are added with a new tuple to create another tuple.
 Example :
t=(‘a’,’b’,’c’,’d’,’e’)
t[1]=’B’
typeError:’tuple’ object does not support item assignment
 Instead of modifying an element in the tuple sequence, it is obvious to simply replace
one tuple with another.
 Program:
t=('a','b','c','d','e')
t1=('A',)+t[1:]
print (t1)
 Output:
('A', 'b', 'c', 'd', 'e')

4.10.2.4 Delete Tuple Elements


 It is impossible to delete a single element in the tuple.
 To delete an entire tuple, the keyword del is used
 Program:
t=(2,3,4,5)
print (t)
del t
 Output:
PPG INSTITUTE OF TECHNOLOGY Page 19
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

(2,3,4,5)

4.10.2.5 Traverse
 The most common way to traverse the elements of a tuple is with a for loop.
 Example:
 t=(1,2)
for i in t:
   print(i)
 Output:
1
2

4.11 TUPLE ASSIGNMENT


 Python has a very powerful tuple assignment feature that allows a tuple of variables
on the left of an assignment to be assigned values from a tuple on the right of the
assignment.
 One requirement is that the number of variables on the left must match the number of
elements in the tuple.
 Once in a while, it is useful to swap the values of two variables. With conventional
assignment statements, we have to use a temporary variable.

 For example, to swap a and b:

temp = a
a=b
b = temp

 Tuple assignment solves this problem neatly:

(a,b) = (b,a)

 The left side is a tuple of variables; the right side is a tuple of values.
 Each value is assigned to its respective variable.
PPG INSTITUTE OF TECHNOLOGY Page 20
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 All the expressions on the right side are evaluated before any of the assignments.
 Naturally, the number of variables on the left and the number of values on the right
have to be the same.

>>>(a,b,c,d)=(1,2,3)
ValueError: need more than 3 values to unpack

Example Program
Swapping of two numbers
a=input("Enter the value of a")
b=input("Enter the value of b")
print("Value of a and b before swapping",a,b)
(a,b)=(b,a)
print("Value of a and b after swapping",a,b)
Output:
Enter the value of a 10
Enter the value of b 20
Value of a and b before swapping 10 20
Value of a and b after swapping 20 10

4.12 TUPLES AS RETURN VALUES


 Function usually return one value but if the value is a tuple then the function can
return multiple values
Example
Divide 2 integers and compute the quotient and remainder
 The built in function divmod takes 2 argument or integer value and return 2 values:
Quotient and remainder
Program:
def div(a,b):
return a/b,a%b
print('Quotient and Remainder is:')
mytuple=divmod(7,3)

PPG INSTITUTE OF TECHNOLOGY Page 21


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print (mytuple)
Output:
Quotient and Remainder is:
(2, 1)

4.13 DICTIONARIES:
 A dictionary contains a collection of indices, which are called keys, and a collection
of values.
 Each key is associated with a single value. The association of a key and a value is
called a key-value pair or sometimes an item.
 A Dictionary may contain any data type and is mutable.
 Its keys, however, are mutable and can only be a string, tuple or a number. Values
stored on a dictionary can only be accessed through the keys.
1. Creating a Dictionary:
 There are several ways to create a new list; the simplest is to enclose the elements in
squiggly-brackets { }.
 In addition to the curly braces, there are also colons (:) throughout the dictionary.

 Syntax:
#To create an empty dictionary:
dict= {}
#To create a dictionary with key-value pairs:
dict={key1:value1,key2:vlaue2,key3=value3}
 key = User defined variable names
 value= Values assigned for the key
 Example
Book = { Name: ‘Programming in C’, Price:1000 }
 The function dict creates a new dictionary with no items.
>>>d=dict()
>>>d
{}
2. Accessing Elements on a Dictionary:
PPG INSTITUTE OF TECHNOLOGY Page 22
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 A Dictionary is an unordered data type. Hence we can’t use the indexing operator to
access the values. We will have to use the key to access the associated value.
 To access dictionary elements, We can either place the keys [] inside square brackets
or use the get() method.
 Example 1
# To access data by using the keys:
>>>my_dict = {'Name': 'Sachin', 'Age': 7, 'Class': 'First'}
>>>my_dict ['Name']
'Sachin'
>>>my_dict ['Class']
'First'
 Example 2
# To access the same values with the get() method :
>>>my_dict = {'Name': 'Sachin', 'Age': 7, 'Class': 'First'}
>>>my_dict.get ('Name')
>>>my_dict.get ('Class')

Output
'Sachin'
'First'
3. Adding and Modifying Entries To A Dictionary
 A dictionary can be updated by adding a new entry or a key-value pair, modifying an
existing entry, or deleting an existing entry
i) Adding Dictionary Entries
 Python evaluates the new entry and checks if there is the similar key in the current
dictionary.
 If there is none, then it appends the key: value pair.
 If the key already exists, then it updates the value of the existing key.
 Syntax:
dict_name [key]=b
Where b is the key-value pair to be the dict_name dictionary.
 Example:
# To add a new key-value pair, to the already existing dictionary
PPG INSTITUTE OF TECHNOLOGY Page 23
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

>>>my_dict = {'Name': 'Sachin', 'Age': 7, 'Class': 'First'}


>>>my_dict [‘Status’]=’regular’
>>>my_dict # To check the updated dictionary
Output:
{'Name': 'Sachin', 'Age': 7, 'Class': 'First', 'Status': 'regular'}

ii) Modifying Dictionary Entries


 To modify the current value, use the assignment operator (=) to specify the new value
to be associated with the key.
 Example:
# Modifying the value of class from First to Second:
>>>my_dict = {'Name': 'Sachin', 'Age': 7, 'Class': 'First'}
>>>my_dict [‘Class’]=’Second’
>>>my_dict # To check the updated dictionary
Output:
{'Name': 'Sachin', 'Age': 7, 'Class': 'Second', 'Status': 'regular'}
4. Traverse:
 The most common way to traverse the elements of a dictionary is with a for loop.
d={1:'one',2:'two'}
for i in d:
   print(i,d[i]))
 Output:
1 one
2 two
5. Deleting a Dictionary
 The del keyword is used to delete a dictionary.
 Syntax:
del dict_name
 Example:
# To delete the my_dict dictionary, we will use the del keyword
>>>my_dict = {'Ocean': 'Indian Ocean', 'Sea': 'Arabian', 'river': 'Cauvery'}
>>>del my_dict
>>>my_dict
PPG INSTITUTE OF TECHNOLOGY Page 24
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Output:
Traceback (most recent call last):
File "python", line 3, in <module>
NameError: name 'my_dict' is not defined

4.13.1 Dictionary Methods


1. keys():
 The keys() returns a view object that displays a list of all the keys in a given
dictionary.
 Example:
d={1:'one',2:'two'}
print(d.keys())

 Output:
dict_keys([1, 2])

2. values():
 The values() method returns a view object that displays a list of all values in a given
dictionary.
 Example:
d={1:'one',2:'two'}
print(d.values())
 Output:
dict_values(['one', 'two'])
3. items():
 The items() method returns a view object that displays a list of a given dictionary's
(key, value) tuple pair.
 Example:
d={1:'one',2:'two'}
print(d.items())
 Output:
dict_items([(1, 'one'), (2, 'two')])
4. clear():
PPG INSTITUTE OF TECHNOLOGY Page 25
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 The clear() method removes all items from the dictionary.


 Example:
d={1:'one',2:'two'}
d.clear()
print(d)
 Output:
{}
5. pop():
 The pop() method removes and returns an element from a dictionary having the given
key.
 Example:
d={1:'one',2:'two'}
print(d.pop(1))
 Output:
one
6. copy():
 They copy() method returns a shallow copy of the dictionary.
 Example:
d={1:'one',2:'two'}
newd=d.copy()
print(newd)
 Output:
{1:'one',2:'two'}

7. get():
 The get() method returns the value for the specified key if key is in dictionary.
 Example:
d={1:'one',2:'two'}
print(d.get(1,"Not found"))
print(d.get(3,"Not found"))
 Output:
one
Not found
PPG INSTITUTE OF TECHNOLOGY Page 26
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

8. setdefault():
 The method setdefault() is similar to get(), but will set dict[key]=default if key is not
already in dict.
 Syntax
dict.setdefault(key, default=None)
 Parameters
key − This is the key to be searched.
default − This is the Value to be returned in case key is not found.

 Return Value
This method returns the key value available in the dictionary and if given key
is not available then it will return provided default value.
 Example:
>>>my_dict={'a': 'car', 'b': 'van', 'c': 'bus'}
>>>my_dict.setdefault('c',None)
 Output:
bus
9.update():
 The update() method adds element(s) to the dictionary if the key is not in the
dictionary. If the key is in the dictionary, it updates the key with the new value.
 Example:
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
d.update(d1)
print(d)
 Output:
{1: "one", 2: "two"}
10. popitem()
 The popitem () method is used to remove a random key-value pair from a dictionary.
 The method does not take an argument and returns the deleted key-value pair.
 Example:
>>>my_dict = {'Ocean': 'Indian Ocean', 'Sea': 'Arabian', 'river': 'Cauvery'}
PPG INSTITUTE OF TECHNOLOGY Page 27
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

>>>my_dict.popitem ()
>>>my_dict #Updated Dictionary
 Output:
{'Ocean': 'Indian Ocean', 'Sea': 'Arabian'}

4.13.2 Dictionary Membership Test


The membership operators ‘in’ and ‘not in’ to check whether a specific key exists or
not on the dictionary.
Program:
even={ 2: 'abc',4: 'def',6: 'ghi',8: 'jkl'}
print(2 in even)
print(12 not in even)
print(6 in even)
Output
True
True
True

4.13.3 Using Built-in functions with Dictionaries:

S
Function Description Example Output
No
1 len() Returns the dict = {'Name': 'Zara', 'Age': 7}; Length : 2
number of items print ("Length : %d" % len(dict))
in the dictionary
2 str() Returns a ict = {'Name': 'Zara', 'Age': 7}; Equivalent String :
printable string print ("Equivalent String : %s" {'Name': 'Zara', 'Age':
representation of % str (dict)) 7}
a dictionary
3 type() Returns the type dict = {'Name': 'Zara', 'Age': 7}; Variable Type : <class
of the passed print ("Variable Type : %s" % 'dict'>

PPG INSTITUTE OF TECHNOLOGY Page 28


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

variable type (dict))


4 dict() It can be used to pairs=[("cat","kitten"), {'cat': 'kitten', 'dog':
create a ("dog","puppy"),("lamb","ewe"), 'puppy', 'lamb': 'ewe',
dictionary from a ("lion", 'lion': 'cub'}
list of tuple pairs "cub")]
print(dict(pairs))
4.13.4 Dictionary Comprehension
Description:
It is a concise way of creating a new dictionary from a python iterable.It consists of a
key-value expression and a ‘for statement’ enclosed in curly braces{}.
Example 1:
squares={x : x **2 for x in range(10)}
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

A dictionary comprehension may hold more than one conditional statement (for of if
statements). In the above example, an ‘If statement’ may be added to filter out the desired
items to build a new dictionary.
Example 2:
even_squares={x : x **2 for x in range(10) if x%2 == 0}
print(even_squares)
Output :
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Example 3:
odd_squares={x : x **2 for x in range(10) if x%2 == 1}
print(odd_squares)
Output:
{1:1,3:9,5:25,7:49,9:81}

4.14 LIST COMPREHENSIONS:


 List comprehensions provide a concise way to create lists.

PPG INSTITUTE OF TECHNOLOGY Page 29


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 A list comprehension consists of brackets containing an expression followed by a for


clause, then zero or more for or if clauses.
 The result will be a new list resulting from evaluating the expression in the context of
the for and if clauses which follow it.

 In Python, list comprehensions are constructed like so:


list_variable = [x for x in iterable]
Example 1:
list = [letter for letter in 'Apple']
print(list)
Output:
['A', 'p', 'p', 'l', 'e']

Example 2:
list = []
for letter in 'Apple':
list.append(letter)
print(list)
Output:
['A', 'p', 'p', 'l', 'e']
a) Using Conditionals With List Comprehensions
Example:
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
fish_list = [fish for fish in fish_tuple if fish != 'octopus']
print(fish_list)
Output:
['blowfish', 'clownfish', 'catfish']
b) List comprehension using mathematical operators, integers, and the range() sequence
type.
Example:
number_list = [x ** 2 for x in range(10) if x % 2 == 0]

PPG INSTITUTE OF TECHNOLOGY Page 30


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

print(number_list)
Output
[0, 4, 16, 36, 64]

c) Nested Loops in a List Comprehension


Example:
my_list=[]
for x in [20, 40, 60]:
for y in [2, 4, 6]:
my_list.append(x*y)
print(my_list)
Output:
[40, 80, 120, 80, 160, 240, 120, 240, 360]

4.15 ILLUSTRATIVE PROBLEMS


1 SELECTION SORT:
 The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the
beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

PPG INSTITUTE OF TECHNOLOGY Page 31


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Program:
def ssort( aList ):
for i in range( len( aList ) ):
least = i
for k in range( i + 1 , len( aList ) ):
if aList[k] < aList[least]:
least = k
swap( aList, least, i )
def swap( A, x, y ):
tmp = A[x]
A[x] = A[y]
A[y] = tmp
a=[]
n=int(input("Enter Upper Limit:"))
print("Enter the elements")
for i in range(n):
a.append(int(input()))
ssort(a)
print('After Sorting:',a)

Output

PPG INSTITUTE OF TECHNOLOGY Page 32


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Enter Upper Limit: 5


Enter the elements
2 3 1 4 5
After Sorting: [1 2 3 4 5]

2. INSERTION SORT
 Insertion sort is a simple sorting algorithm that works the way we sort playing cards
in our hands.

Program:
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = [54,26,93,17,77,31,44,55,20]
insertionSort(alist)
print(alist)

PPG INSTITUTE OF TECHNOLOGY Page 33


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Output:
[17, 20, 26, 31, 44, 54, 55, 77, 93]

3. MERGESORT
 In merge sort the unsorted list is divided into N sublists, each having one element,
because a list consisting of one element is always sorted.
 Then, it repeatedly merges these sublists, to produce new sorted sublists, and in the
end, only one sorted list is produced.

Program:
myList = [12, 54, 3, 85, 73, 99, 37, 29]
def mergeSort(myList):
if len(myList)< 2: # if len(list) < 2, list already sorted
return myList
mid = int(len(myList)/2) # if len(list)>= 2 then divide list
x = mergeSort(myList[:mid]) # into two halves x= leftpart of myList
y = mergeSort(myList[mid:]) # and y = rightpart of myList
output = []

PPG INSTITUTE OF TECHNOLOGY Page 34


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

i=0
j=0
while i < len(x) and j < len(y):
if x[i] > y[j]:
output.append(y[j]) # sorting right part of myList
j += 1
else:
output.append(x[i]) # sorting left part of myList
i += 1
output += x[i:] # meging and sorting the myList
output += y[j:]
return output
print("The sorted list is: ", mergeSort(myList))

Output:
The sorted list is: [3, 12, 29, 37, 54, 73, 85, 99]

4. HISTOGRAM:
 It is a statistical term for a collection of counters(or frequencies).
Program:
def histogram(s):
    d = dict()
    for c in s:
        if c not in d:
            d[c] = 1
        else:
            d[c] += 1
    return d

s=input()
print(histogram(s))

PPG INSTITUTE OF TECHNOLOGY Page 35


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Output:
united
{'d': 1, 'e': 1, 'i': 1, 'n': 1, 't': 1, 'u': 1}

PPG INSTITUTE OF TECHNOLOGY Page 36

You might also like