0% found this document useful (0 votes)
76 views26 pages

Working With Lists and Dictionaries CH-4

The document discusses lists and dictionaries in Python. It introduces lists as ordered sequences that can contain elements of different data types. Lists are mutable, meaning their contents can be changed after creation. Elements in a list are accessed using indexes, and lists support various operations like accessing, traversing, and manipulating elements. Dictionaries are also introduced, which store elements as key-value pairs that can be traversed and manipulated.

Uploaded by

Tanisha Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views26 pages

Working With Lists and Dictionaries CH-4

The document discusses lists and dictionaries in Python. It introduces lists as ordered sequences that can contain elements of different data types. Lists are mutable, meaning their contents can be changed after creation. Elements in a list are accessed using indexes, and lists support various operations like accessing, traversing, and manipulating elements. Dictionaries are also introduced, which store elements as key-value pairs that can be traversed and manipulated.

Uploaded by

Tanisha Jain
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Downloaded from https:// www.studiestoday.

com
Downloaded from https:// www.dkgoelsolutions.com

Working with Chapter


Lists and
Dictionaries 4

om
.c
ns
io
In this chapter

ut » Introduction to List
ol
» List Operations
ls

“Computer Science is a science of » Traversing a List


oe

abstraction – creating the right model for » List Methods and Built-
kg

a problem and devising the appropriate in Functions

mechanizable techniques to solve it.” » List Manipulation


.d

» Introduction to
w

Dictionaries
w

— A. Aho and J. Ullman » Traversing a Dictionary


//w

» Dictionary Methods and


s:

Built-in Functions
tp

» Manipulating
4.1 IntroductIon LIst
ht

to Dictionaries
The data type list is an ordered sequence which is
mutable and made up of one or more elements. Unlike a
string which consists of only characters, a list can have
elements of different data types such as integer, float,
string, tuple or even another list. A list is very useful to
group elements of mixed data types. Elements of a list
are enclosed in square brackets and are separated by
comma.
Example 4.1
#list1 is the list of six even numbers
>>> list1 = [2,4,6,8,10,12]
>>> print(list1)
[2, 4, 6, 8, 10, 12]

2020-21

Chap 4.indd 55
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

56 InformatIcs PractIces – class XI

notes #list2 is the list of vowels


>>> list2 = ['a','e','i','o','u']
>>> print(list2)
['a', 'e', 'i', 'o', 'u']

#list3 is the list of mixed data types


>>> list3 = [100,23.5,'Hello']
>>> print(list3)
[100, 23.5, 'Hello']

#list4 is the list of lists called nested


#list
>>> list4 =[['Physics',101],['Chemistry',202],
['Mathematics',303]]

om
>>> print(list4)
[['Physics', 101], ['Chemistry', 202],

.c
['Mathematics', 303]]

ns
4.1.1 Accessing Elements in a List

io
Each element in list is accessed using value called index.
ut
The fist index value is 0, the second index is 1 and so
ol
on. Elements in the list are assigned index values in
ls

increasing order sterling from 0.


oe

To access an element, use square brackets with


the index [] value of that element. We may also use
kg

negative index value to access elements starting from


.d

the last element in the list, having index value -0.


w

#initialing a list named list1


w

>>> list1 = [2,4,6,8,10,12]


>>> list1[0] #returns first element of list1
//w

2
s:

>>> list1[3] #returns fourth element of list1


tp

8
#Out of range index value for the list returns error
ht

>>> list1[15]
IndexError: list index out of range
#an expression resulting in an integer index
>>> list1[1+4]
12
>>> list1[-1] #return first element from right
12
#length of the list1 is assigned to n
>>> n = len(list1)
>>> print(n)
6
#Get the last element of the list1
>>> list1[n-1]
12

2020-21

Chap 4.indd 56
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 57

#Get the first element of list1


>>> list1[-n]
2

4.1.2 Lists are Mutable


In Python, lists are mutable. It means that the contents
of the list can be changed after it has been created.
#List list1 of colors
>>> list1 = ['Red','Green','Blue','Orange']
#change/override the fourth element of list1
>>> list1[3] = 'Black'
>>> list1 #print the modified list list1
['Red', 'Green', 'Blue', 'Black']

om
4.2 LIst operatIons

.c
The data type list allows manipulation of its contents

ns
through various operations as shown below.

io
4.2.1 Concatenation
Python allows us to join two or more lists using ut Concatenation is the
ol
merging of two or
concatenation operator using symbol +. more values. Example:
ls

#list1 is list of first five odd integers we can concatenate


oe

>>> list1 = [1,3,5,7,9] strings together.


#list2 is list of first five even integers
kg

>>> list2 = [2,4,6,8,10]


.d

#Get elements of list1 followed by list2


w

>>> list1 + list2


[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
w

>>> list3 = ['Red','Green','Blue']


//w

>>> list4 = ['Cyan', 'Magenta', 'Yellow'


,'Black']
s:

>>> list3 + list4


tp

['Red','Green','Blue','Cyan','Magenta',
ht

'Yellow','Black']
Note that, there is no change in original lists i.e.,
list1, list2, list3, list4 remain the same after
concatenation operation. If we want to use the result of
two concatenated lists, we should use an assignment
operator.
For example,
#Join list 2 at the end of list
>>> new List = list 1 + list 2
[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
>> new list The concatenation operator '+’ requires that
the operands should be of list type only. If we try to
concatenate a list with elements of some other data
type, TypeError occurs.

2020-21

Chap 4.indd 57
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

58 InformatIcs PractIces – class XI

notes >>> list1 = [1,2,3]


>>> str1 = "abc"
>>> list1 + str1
TypeError: can only concatenate list (not
"str") to list

4.2.2 Repetition
Python allows us to replicate the contents of a list using
repetition operator depicted by symbol *.
>>> list1 = ['Hello']
#elements of list1 repeated 4 times
>>> list1 * 4
['Hello', 'Hello', 'Hello', 'Hello']

om
4.2.3 Membership

.c
The membership operator in checks if the element

ns
is present in the list and returns True, else returns
False.

io
>>> list1 = ['Red','Green','Blue']
>>> 'Green' in list1
ut
ol
True
>>> 'Cyan' in list1
ls

False
oe

The Operator not in transpose returns True if the


kg

element is not present in the list, else it returns False.


>>> list1 = ['Red','Green','Blue']
.d

>>> 'Cyan' not in list1


w

True
w

>>> 'Green' not in list1


//w

False

4.2.4 Slicing
s:
tp

Slicing operations allow us to create new list by taking


out elements from an existing list.
ht

>>> list1 =['Red','Green','Blue','Cyan',


'Magenta','Yellow','Black']
#subject from indexes 2 to 5 of list 1
>>> list1[2:6]
['Blue', 'Cyan', 'Magenta', 'Yellow']

#list1 is truncated to the end of the list


>>> list1[2:20] #second index is out of range
['Blue', 'Cyan', 'Magenta', 'Yellow',
'Black']

>>> list1[7:2] #first index > second index


[] #results in an empty list

2020-21

Chap 4.indd 58
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 59

#return sublist from index 0 to 4


>>> list1[:5] #first index missing
['Red','Green','Blue','Cyan','Magenta']

#slicing with a given step size


>>> list1[0:6:2]
['Red','Blue','Magenta']
#negative indexes
#elements at index -6,-5,-4,-3 are sliced
>>> list1[-6:-2]
['Green','Blue','Cyan','Magenta']

#both first and last index missing

om
>>> list1[::2] #step size 2 on entire list
['Red','Blue','Magenta','Black']

.c
ns
#Access list in the reverse order using
negative step size

io
>>> list1[::-1]
['Black','Yellow','Magenta','Cyan','Blue', ut
ol
'Green','Red']
ls
oe

4.3 traversIng a LIst


kg

We can access each element of the list or traverse a list


using a for loop or a while loop.
.d

(A) List traversal using for loop:


w

>>> list1 = ['Red','Green','Blue','Yellow',


w

'Black']
//w

>>> for item in list1:


print(item) len (list1) returns
s:

Output: the length or total


tp

Red number of elements of


Green list1.
ht

range(n) returns a
Blue
sequence of numbers
Yellow starting from 0,
Black increases by 1 and ends
Another way of accessing the elements of the list is at n-1 (one number
less than the specified
using range() and len() functions: number i.e. is)
>>> for i in range(len(list1)):
print(list1[i])
Output:
Red
Green
Blue
Yellow
Black

2020-21

Chap 4.indd 59
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

60 InformatIcs PractIces – class XI

4.4 LIst Methods and BuILt-In FunctIons


The data type list has several built-in methods that
are useful in programming. Some of them are listed in
Table 4.1.

Table 4.1 Built-in functions for list manipulation


Method Description Example

len() Returns the length of the list passed as >>> list1 = [10,20,30,40,50]
the argument >>> len(list1)
5

om
list() Creates an empty list if no argument is >>> list1 = list()
passed >>> list1

.c
[ ]

ns
io
Creates a list if a sequence is passed as ut
>>> str1= 'aeiou'
>>> list1 = list(str1)
ol
an argument >>> list1
ls
['a', 'e', 'i', 'o', 'u']
oe
kg

append() Appends a single element passed as an >>> list1 = [10,20,30,40]


argument at the end of the list >>> list1.append(50)
.d

>>> list1
w

A list can also be appended as an ele- [10, 20, 30, 40, 50]
ment to an existing list >>> list1 = [10,20,30,40]
w

>>> list1.append([50,60])
//w

>>> list1
[10, 20, 30, 40, [50, 60]]
s:
tp

extend() Appends each element of the list passed >>> list1 = [10,20,30]
ht

as argument at the end of the given list >>> list2 = [40,50]


>>> list1.extend(list2)
>>> list1
[10, 20, 30, 40, 50]

insert() Inserts an element at a particular index >>> list1 = [10,20,30,40,50]


in the list #inserts element 25 at index value 2
>>> list1.insert(2,25)
>>> list1
[10, 20, 25, 30, 40, 50]
>>> list1.insert(0,100)
>>> list1
[100, 10, 20, 25, 30, 40, 50]

2020-21

Chap 4.indd 60
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 61

count() Returns the number of times a given >>> list1 = [10,20,30,10,40,10]


element appears in the list >>> list1.count(10)
3
>>> list1.count(90)
0

find() Returns index of the first occurrence of >>> list1 = [10,20,30,20,40,10]


the element in the list. If the element is >>> list1.index(20)
not present, ValueError is generated 1
>>> list1.index(90)
ValueError: 90 is not in list
remove() Removes the given element from the >>> list1 = [10,20,30,40,50,30]
list. If the element is present multi- >>> list1.remove(30)
ple times, only the first occurrence is >>> list1

om
removed. If the element is not present, [10, 20, 40, 50, 30]
then ValueError is generated >>> list1.remove(90)

.c
ValueError:list.remove(x):x not in

ns
list

io
pop() Returns the element whose index is >>> list1 = [10,20,30,40,50,60]
passed as argument to this function
and also removes it from the list. If no ut
>>> list1.pop(3)
40
ol
argument is given, then it returns and >>> list1
ls
removes the last element of the list [10, 20, 30, 50, 60]
oe

>>> list1 = [10,20,30,40,50,60]


>>> list1.pop()
kg

60
>>> list1
.d

[10, 20, 30, 40, 50]


w

reverse() Reverses the order of elements in the >>> list1 = [34,66,12,89,28,99]


w

given list >>> list1.reverse()


>>> list1
//w

[ 99, 28, 89, 12, 66, 34]


s:

>>> list1 = [ 'Tiger' ,'Zebra' ,


tp

'Lion' , 'Cat' ,'Elephant' ,'Dog']


ht

>>> list1.reverse()
>>> list1
['Dog', 'Elephant', 'Cat', 'Lion',
'Zebra', 'Tiger']
sort() Sorts the elements of the given list in >>>list1 = ['Tiger','Zebra','Lion',
place 'Cat', 'Elephant' ,'Dog']
>>> list1.sort()
>>> list1
['Cat', 'Dog', 'Elephant', 'Lion',
'Tiger', 'Zebra']

>>> list1 = [34,66,12,89,28,99]


>>> list1.sort(reverse = True)
>>>list1
[99,89,66,34,28,12]

2020-21

Chap 4.indd 61
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

62 InformatIcs PractIces – class XI

sorted() It takes a list as parameter and creates >>>list1 = [23,45,11,67,85,56]


a new list consisting of the same ele- >>> list2 = sorted(list1)
ments but arranged in ascending order >>> list1
[23, 45, 11, 67, 85, 56]
>>> list2
[11, 23, 45, 56, 67, 85]
min() Returns minimum or smallest element >>> list1 = [34,12,63,39,92,44]
of the list >>> min(list1)
12
max() Returns maximum or largest element of >>> max(list1)
the list 92
sum() Returns sum of the elements of the list >>> sum(list1)
284

om
4.5 LIst ManIpuLatIon

.c
In this chapter, we have learnt to create a list and the different ways to

ns
manipulate lists. In the following programs, we will apply the various list

io
manipulation methods.

ut
Program 4-1 Write a program to allow user to perform any those list operation
ol
given in a menu. The menu is:
ls
oe

1. Append an element
2. Insert an element
kg

3. Append a list to the given list


.d

4. Modify an existing element


w

5. Delete an existing element from its position


w

6. Delete an existing element with a given value


//w

7. Sort the list in the ascending order


s:

8. Sort the list in descending order


tp

9. Display the list.


ht

#Program 4-1
#Menu driven program to do various list operations
myList = [22,4,16,38,13] #myList having 5 elements
choice = 0
For attempt in range (3): print ("Attempt number:", attempt)
print("The list 'myList' has the following elements", myList)
print("\nL I S T O P E R A T I O N S")
print(" 1. Append an element")
print(" 2. Insert an element at the desired position")
print(" 3. Append a list to the given list")
print(" 4. Modify an existing element")
print(" 5. Delete an existing element by its position")
print(" 6. Delete an existing element by its value")

2020-21

Chap 4.indd 62
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 63

print(" 7. Sort the list in ascending order")


print(" 8. Sort the list in descending order")
print(" 9. Display the list")
choice = int(input("ENTER YOUR CHOICE (1-9): "))

#append element
if choice == 1:
element = eval(input("Enter the element to be appended: "))
myList.append(element)
print("The element has been appended\n")

#insert an element at desired position


elif choice == 2:
element = eval(input("Enter the element to be inserted: "))

om
pos = int(input("Enter the position:"))
myList.insert(pos,element)

.c
print("The element has been inserted\n")

ns
io
#append a list to the given list
elif choice == 3:
ut
newList = eval(input("Enter the list to be appended: "))
ol
myList.extend(newList)
ls
print("The list has been appended\n")
oe

#modify an existing element


kg

elif choice == 4:
i = int(input("Enter the position of the element to be
.d

modified: "))
w

if i < len(myList):
w

newElement = eval(input("Enter the new element: "))


//w

oldElement = myList[i]
myList[i] = newElement
s:

print("The element",oldElement,"has been modified\n")


tp

else:
print("Position of the element is more then the length
ht

of list")

#delete an existing element by position


elif choice == 5:
i = int(input("Enter the position of the element to be
deleted: "))
if i < len(myList):
element = myList.pop(i)
print("The element",element,"has been deleted\n")
else:
print("\nPosition of the element is more then the length
of list")

2020-21

Chap 4.indd 63
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

64 InformatIcs PractIces – class XI

#delete an existing element by value


elif choice == 6:
element = int(input("\nEnter the element to be deleted: "))
if element in myList:
myList.remove(element)
print("\nThe element",element,"has been deleted\n")
else:
print("\nElement",element,"is not present in the list")

#list in sorted order


elif choice == 7:
myList.sort()
print("\nThe list has been sorted")

om
#list in reverse sorted order

.c
elif choice == 8:

ns
myList.sort(reverse = True)

io
print("\nThe list has been sorted in reverse order")

#display the list ut


ol
elif choice == 9:
ls

print("\nThe list is:", myList)


oe

else:
kg

print("Choice is not valid")


Output:
.d

The list 'myList' has the following elements [22, 4, 16, 38, 13]
w

Attempt number : 1
w

L I S T O P E R A T I O N S
//w

1. Append an element
2. Insert an element at the desired position
s:

3. Append a list to the given list


tp

4. Modify an existing element


ht

5. Delete an existing element by its position


6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
ENTER YOUR CHOICE (1-10): 8

The list has been sorted in reverse order


The list 'myList' has the following elements [38, 22, 16, 13, 4]
Attempt number : 2
L I S T O P E R A T I O N S
1. Append an element

2020-21

Chap 4.indd 64
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 65

2. Insert an element at the desired position


3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position
6. Delete an existing element by its value
7. Sort the list in ascending order
8. Sort the list in descending order
9. Display the list
ENTER YOUR CHOICE (1-9) 5
Enter the position of the element to be deleted: 2
The element 16 has been deleted

om
The list 'myList' has the following elements [38, 22, 13, 4]
Attempt number : 3
L I S T O P E R A T I O N S

.c
1. Append an element

ns
2. Insert an element at the desired position

io
3. Append a list to the given list
4. Modify an existing element
5. Delete an existing element by its position ut
ol
6. Delete an existing element by its value
ls

7. Sort the list in ascending order


oe

8. Sort the list in descending order


kg

9. Display the list


.d

ENTER YOUR CHOICE (1-9) 10


choice is not valid
w
w

Program 4-2 A program to calculate average marks


//w

of n students where n is entered by


the user.
s:
tp

#Program 4-2
#create an empty list
ht

list1 = []
print("How many students marks you want to enter: ")
n = int(input())
for i in range(0,n):
print("Enter marks of student",(i+1),":")
marks = int(input())
#append marks in the list
list1.append(marks)
#initialize total
total = 0
for marks in list1:

2020-21

Chap 4.indd 65
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

66 InformatIcs PractIces – class XI

#add marks to total


total = total + marks
average = total / n
print("Average marks of",n,"students is:",average)
Output:
How many students marks you want to enter:
5
Enter marks of student 1:
45
Enter marks of student 2:
89
Enter marks of student 3:
79

om
Enter marks of student 4:
76

.c
Enter marks of student 5:

ns
55
Average marks of 5 students is: 68.8

io
Program 4-3 Write a program to check if a number is
present in the list or not. If the number ut
ol
is present, print the position of the
ls

number. Print an appropriate message if


oe

the number is not present in the list.


kg

#Program 4-3
list1 = [] #Create an empty list
.d

print("How many numbers do you want to enter in the list: ")


w

maximum = int(input())
w

print("Enter a list of numbers: ")


//w

for i in range(0,maximum):
n = int(input())
s:

list1.append(n) #append numbers to the list


tp

num = int(input("Enter the number to be searched: "))


ht

position = -1
for i in range (0, lin (list1)
if list1[i] == num: #number is present
position = i+1 #save the position of number
if position == -1 :
print("Number",num,"is not present in the list")
else:
print("Number",num,"is present at",position + 1, "position")
Output:
How many numbers do you want to enter in the list
5

2020-21

Chap 4.indd 66
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 67

Enter a list of numbers:


23
567
12
89
324
Enter the number to be searched:12
Number 12 is present at 3 position

4.6 IntroductIon to dIctIonarIes

The data type dictionary falls under mapping. It is a


mapping between a set of keys and a set of values. The

om
key-value pair is called an item. A key is separated from
its value by a colon(:) and consecutive items are separated

.c
by commas. Items in dictionaries are unordered, so we

ns
may not get back the data in the same order in which

io
we had entered the data initially in the dictionary.
4.6.1 Creating a Dictionary ut
ol
To create a dictionary, the items entered are separated
ls
by commas and enclosed in curly braces. Each item is
oe

a key value pair, separated through colon (:). The keys


in the dictionary must be unique and should be of any
kg

immutable data type i.e. number, string or tuple. The


.d

values can be repeated and can be of any data type.


w

Example 4.2
w

#dict1 is an empty dictionary


>>> dict1 = {}
//w

>>> dict1
{}
s:

#dict3 is the dictionary that maps names of


tp

#the students to marks in percentage


ht

>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,


'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85}

4.6.2 Accessing Items in a Dictionary


We have already seen that the items of a sequence
(string, list and tuple) are accessed using a technique
called indexing. The items of a dictionary are accessed
via the keys rather than via their relative positions
or indices. Each key serves as the index and maps to
a value.

2020-21

Chap 4.indd 67
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

68 InformatIcs PractIces – class XI

notes The following example shows how a dictionary


returns the value corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
#using unspecified key
>>> dict3['Shyam']
KeyError: 'Shyam'
In the above examples the key 'Ram' always maps to the

om
value 89 and key 'Sangeeta' always maps to the value
85. So the order of items does not matter. If the key is not

.c
present in the dictionary we get KeyError.

ns
4.6.3 Membership Operation

io
The membership operator in checks if the key is present
ut
in the dictionary and returns True, else it returns False.
ol
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
ls
'Sangeeta':85}
oe

>>> 'Suhel' in dict1


True
kg

The not in operator returns True if the key is not


.d

present in the dictionary, else it returns False.


w

>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,


'Sangeeta':85}
w

>>> 'Suhel' not in dict1


//w

False
s:

4.6.4 Dictionaries are Mutable


tp

Dictionaries are mutable which implies that the


ht

contents of the dictionary can be changed after it has


been created.
(A) Adding a new item
We can add a new item to the dictionary as shown in
the following example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85, 'Meena': 78}

2020-21

Chap 4.indd 68
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:20 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 69

(B) Modifying an existing item


The existing dictionary can be modified by just
overwriting the key-value pair. Example to modify a
given item in the dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
#Marks of Suhel changed to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,
'Sangeeta': 85}

om
4.7 traversIng a dIctIonary
We can access each item of the dictionary or traverse a

.c
dictionary using for loop.

ns
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}

io
Method 1:
>>> for key in dict1: ut
ol
print(key,':',dict1[key])
ls

Mohan: 95
oe

Ram: 89
Suhel: 92
kg

Sangeeta: 85
.d

Method 2:
w

>>> for key,value in dict1.items():


w

print(key,':',value)
//w

Mohan: 95
Ram: 89
s:

Suhel: 92
tp

Sangeeta: 85
ht

4.8 dIctIonary Methods and BuILt-In FunctIons


Python provides many functions to work on dictionaries.
Table 4.2 lists some of the commonly used dictionary
methods.
Table 4.2 Built-in functions and methods for dictionary
Method Description Example
len() Returns the length or number of >>> dict1 = {'Mohan':95,'Ram':89,
key: value pairs of the dictionary 'Suhel':92, 'Sangeeta':85}
passed as the argument >>> len(dict1)
4

2020-21

Chap 4.indd 69
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

70 InformatIcs PractIces – class XI

dict() Creates a dictionary from a pair1 = [('Mohan',95),('Ram',89),


sequence of key-value pairs ('Suhel',92),('Sangeeta',85)]
>>> pair1
[('Mohan', 95), ('Ram', 89), ('Suhel',
92), ('Sangeeta', 85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85}

keys() Returns a list of keys in the >>> dict1 = {'Mohan':95, 'Ram':89,


dictionary 'Suhel':92, 'Sangeeta':85}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel',

om
'Sangeeta'])

.c
values() Returns a list of values in the >>> dict1 = {'Mohan':95, 'Ram':89,

ns
dictionary 'Suhel':92, 'Sangeeta':85}
>>> dict1.values()

io
dict_values([95, 89, 92, 85])

ut
ol
items() Returns a list of tuples (key — >>> dict1 = {'Mohan':95, 'Ram':89,
ls
value) pair 'Suhel':92, 'Sangeeta':85}
oe

>>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram', 89),
kg

('Suhel', 92), ('Sangeeta', 85)])


.d

get() Returns the value corresponding >>> dict1 = {'Mohan':95, 'Ram':89,


w

to the key passed as the argument 'Suhel':92, 'Sangeeta':85}


w

>>> dict1.get('Sangeeta')
If the key is not present in the 85
//w

dictionary it will return None


>>> dict1.get('Sohan')
s:

>>>
tp

update() appends the key-value pair of >>> dict1 = {'Mohan':95, 'Ram':89,


the dictionary passed as the
ht

'Suhel':92, 'Sangeeta':85}
argument to the key-value pair of >>> dict2 = {'Sohan':79,'Geeta':89}
the given dictionary >>> dict1.update(dict2)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}

clear() Deletes or clear all the items of >>> dict1 = {'Mohan':95,'Ram':89,


the dictionary 'Suhel':92, 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{ }

2020-21

Chap 4.indd 70
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 71

del() Deletes the item with the given >>> dict1 = {'Mohan':95,'Ram':89,
key 'Suhel':92, 'Sangeeta':85}
To delete the dictionary from the >>> del dict1['Ram']
memory we write: >>> dict1
del Dict_name
{'Mohan':95,'Suhel':92, 'Sangeeta': 85}

>>> dict1
NameError: name 'dict1' is not defined

4.9 ManIpuLatIng dIctIonarIes

om
In this chapter, we have learnt how to create a
dictionary and apply various methods to manipulate it.

.c
The following examples show the application of those

ns
manipulation methods on dictionaries.

io
(a) Create a dictionary ‘ODD’ of odd numbers between
1 and 10, where the key is the decimal number and
the value is the corresponding number in words. ut
ol
ls
>>> ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}
oe

>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}
kg
.d

(b) Display the keys in dictionary ‘ODD’.


w

>>> ODD.keys()
w

dict_keys([1, 3, 5, 7, 9])
//w

(c) Display the values in dictionary ‘ODD’.


>>> ODD.values()
s:

dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])


tp
ht

(d) Display the items from dictionary ‘ODD’


>>> ODD.items()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9,
'Nine')])

(e) Find the length of the dictionary ‘ODD’.


>>> len(ODD)
5

(f) Check if 7 is present or not in dictionary ‘ODD’


>>> 7 in ODD
True

2020-21

Chap 4.indd 71
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

72 InformatIcs PractIces – class XI

(g) Check if 2 is present or not in dictionary ‘ODD’


>>> 2 in ODD
False

(h) Retrieve the value corresponding to the key 9


>>> ODD.get(9)
'Nine'

(i) Delete the item from the dictionary, corresponding to the key 9. ‘ODD’
>>> del ODD[9]
>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}

om
Program 4-4 σ n number of write a program to enter
names of employees and their salaries

.c
as input and store them in a dictionary.

ns
Here n is to input by the user.

io
#Program 4-4
ut
#Program to create a dictionary which stores names of employees
ol
#and their salary
ls
num = int(input("Enter the number of employees whose data to be
stored: "))
oe

count = 1
kg

employee = dict() #create an empty dictionary


for count in range (n):
.d

name = input("Enter the name of the Employee: ")


w

salary = int(input("Enter the salary: "))


w

employee[name] = salary
//w

print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
s:

print(k,'\t\t',employee[k])
Output:
tp

Enter the number of employees to be stored: 5


ht

Enter the name of the Employee: 'Tarun'


Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000

2020-21

Chap 4.indd 72
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 73

'Joseph' 24000
'Rahul' 30000
'Zoya' 25000

Program 4-5 Write a program to count the number


of times a character appears in a given
string.
#Program 4-5
#Count the number of times a character appears in a given string
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in dic

om
dic[ch] += 1
else:

.c
dic[ch] = 1 #if ch appears for the first time

ns
io
for key in dic:
print(key,':',dic[key])
Output: ut
ol
Enter a string: HelloWorld
ls

H : 1
oe

e : 1
kg

l : 3
o : 2
.d

W : 1
w

r : 1
w

d : 1
//w

Program 4-6 Write a program to convert a number


entered by the user into its corresponding
s:

number in words. for example if the input


tp

is 876 then the output should be ‘Eight


ht

Seven Six’.
# Program 4-6
num = input("Enter any number: ") #number is stored as string
#numberNames is a dictionary of digits and corresponding number
#names
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\
5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}

result = ''
for ch in num:
key = int(ch) #converts character to integer
value = numberNames[key]

2020-21

Chap 4.indd 73
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

74 InformatIcs PractIces – class XI

result = result + ' ' + value


print("The number is:",num)
print("The numberName is:",result)
Output:
Enter any number: 6512
The number is: 6512
The numberName is: Six Five One Two

suMMary

om
Lists are mutable sequences in Python, i.e. we can
change the elements of the list.

.c
• Elements of a list are put in square brackets

ns
separated by comma.

io
List indexing is same as that of list and starts at 0.

ut
Two way indexing allows traversing the list in the
forward as well as in the backward direction.
ol

ls
Operator + concatenates one list to the end of other
oe

list.
• Operator * repeats the content of a list by
kg

specified number of times.


.d

• Membership operator in tells if an element is


w

present in the list or not and not in does the


w

opposite.
//w

• Slicing is used to extract a part of the list.



s:

There are many list manipulation methods. Few


tp

are: len(), list(), append(), extend(), insert(), count(),


find(), remove(), pop(), reverse(), sort(), sorted(),
ht

min(), max(), sum().


• Dictionary is a mapping (non scalar) data type. It
is an unordered collection of key-value pair; key-
value pair are put inside curly braces.
• Each key is separated from its value by a colon.
• Keys are unique and act as the index.
• Keys are of immutable type but values can be
mutable.

2020-21

Chap 4.indd 74
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 75

notes

exercIse
1. What will be the output of the following statements?

a) list1 = [12,32,65,26,80,10]
list1.sort()
print(list1)
b) list1 = [12,32,65,26,80,10]
sorted(list1)
print(list1)

om
c) list1 = [1,2,3,4,5,6,7,8,9,10]
list1[::-2]
list1[:3] + list1[3:]

.c
ns
d) list1 = [1,2,3,4,5]
list1[len(list1)-1]

io
2. Consider the following list myList. What will be
ut
the elements of myList after each of the following
ol
operations?
ls

myList = [10,20,30,40]
oe

a) myList.append([50,60])
b) myList.extend([80,90])
kg

3. What will be the output of the following code segment?


.d

myList = [1,2,3,4,5,6,7,8,9,10]
w

for i in range(0,len(myList)):
w

if i%2 == 0:
//w

print(myList[i])
4. What will be the output of the following code segment?
s:

a) myList = [1,2,3,4,5,6,7,8,9,10]
tp

del myList[3:]
ht

print(myList)

b) myList = [1,2,3,4,5,6,7,8,9,10]
del myList[:5]
print(myList)

c) myList = [1,2,3,4,5,6,7,8,9,10]
del myList[::2]
print(myList)
5. Differentiate between append() and extend() methods
of list.

2020-21

Chap 4.indd 75
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

76 InformatIcs PractIces – class XI

notes 6. Consider a list:


list1 = [6,7,8,9]
What is the difference between the following
operations on list1:
a) lis t1 * 2
b) lis t1 *= 2
c) lis t1 = lis t1 * 2
7. The record of a student (Name, Roll No, Marks in
five subjects and percentage of marks) is stored in
the following list:
stRecord = ['Raman','A-36',[56,98,99,72,69],

om
78.8]
Write Python statements to retrieve the following

.c
information from the list stRecord.

ns
a) Percentage of the student

io
b) Marks in the fifth subject
c) ut
Maximum marks of the student
ol
ls
d) Roll No. of the student
oe

e) Change the name of the student from


‘Raman’ to ‘Raghav’
kg

8. Consider the following dictionary stateCapital:


.d

stateCapital = {"Assam":"Guwahati",
w

"Bihar":"Patna","Maharashtra":"Mumbai",
w

"Rajasthan":"Jaipur"}
//w

Find the output of the following statements:


s:

a) print(stateCapital.get("Bihar"))
tp

b) print(stateCapital.keys())
ht

c) print(stateCapital.values())
d) print(stateCapital.items())
e) print(len(stateCapital))
f) print("Maharashtra" in stateCapital)
g) print(stateCapital.get("Assam"))
h) del stateCapital["Assam"]
print(stateCapital)

prograMMIng proBLeMs
1. Write a program to find the number of times an element
occurs in the list.

2020-21

Chap 4.indd 76
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 77

2. Write a program to read a list of n integers (positive notes


as well as negative). Create two new lists, one having
all positive numbers and the other having all negative
numbers from the given list. Print all three lists.
3. Write a program to find the largest and the second
largest elements in a given list of elements.
4. Write a program to read a list of n integers and find their
median.
Note: The median value of a list of values is the middle one
when they are arranged in order. If there are two middle values
then take their average.
Hint: Use an inbuilt function to sort the list.

om
5. Write a program to read a list of elements. Modify this
list so that it does not contain any duplicate elements i.e.

.c
all elements occurring multiple times in the list should

ns
appear only once.

io
6. Write a program to create a list of elements. Input an
element from the user that has to be inserted in the list.
Also input the position at which it is to be inserted. ut
ol
7. Write a program to read elements of a list and do the
ls

following.
oe

a) The program should ask for the position of the


kg

element to be deleted from the list and delete the


element at the desired position in the list.
.d

b) The program should ask for the value of the element


w

to be deleted from the list and delete this value from


w

the list.
//w

8. Write a Python program to find the highest 2 values in


a dictionary.
s:
tp

9. Write a Python program to create a dictionary from a


string ‘w3resource’ such that each individual character
ht

mates a key and its index value for fist occurrence males
the corresponding value in dictionary.
Expected output : {'3': 1, 's': 4, 'r': 2, 'u': 6, 'w': 0, 'c': 8,
'e': 3, 'o': 5}
10. Write a program to input your friend’s, names and their
phone numbers and store them in the dictionary as the
key-value pair. Perform the following operations on the
dictionary:
a) Display the Name and Phone number for all your
friends.
b) Add a new key-value pair in this dictionary and
display the modified dictionary

2020-21

Chap 4.indd 77
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

78 InformatIcs PractIces – class XI

notes c) Delete a particular friend from the dictionary


d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of names

case study Based QuestIon


For the SMIS System given in Chapter 3, let us do the
following:
1. Write a program to take in the roll number, name and
percentage of marks for n students of Class X and do
the following:
• Accept details of the n students (n is the number

om
of students).

.c
Search details of a particular student on the basis
of roll number and display result.

ns
• Display the result of all the students.

io
• Find the topper amongst them.
• ut
Find the subject toppers amongst them.
ol
ls
(Hint: Use Dictionary, where the key can be roll number
oe

and the value an immutable data type containing name


and percentage.)
kg

case study
.d

1. A bank is a financial institution which is involved in


w

borrowing and lending of money. With advancement


w

in technology, online banking, also known as internet


//w

banking allows customers of a bank to conduct a range


of financial transactions through the bank’s website
s:

anytime, anywhere. As part of initial investigation you


tp

are suggested to:


ht

• Collect a Bank’s application form. After careful


analysis of the form, identify the information
required for opening a savings account. Also
enquire about the rate of interest offered for a
savings account.
• The basic two operations performed on an account
are Deposit and Withdrawal. Write a menu driven
program that accepts either of the two choices
of Deposit and Withdrawal, then accepts an
amount, performs the transaction and accordingly
displays the balance. Remember every bank has
a requirement of minimum balance which needs
to be taken care of during withdrawal operations.

2020-21

Chap 4.indd 78
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

WorkIng WIth lIsts and dIctIonarIes 79

Enquire about the minimum balance required in notes


your bank.
• Collect the interest rates for opening a fixed
deposit in various slabs in a savings bank
account. Remembers rate may be different for
senior citizens.
Finally, write a menu driven program having the
following options (use functions and appropriate data
types):
• Open a savings bank account
• Deposit money
• Withdraw money

om
• Take details such as amount and period for a

.c
Fixed Deposit and display its maturity amount for

ns
a particular customer.
2. Participating in a quiz can be fun as it provides a

io
competitive element. Some educational institutes use
ut
it as a tool to measure knowledge level, abilities and/
ol
or skills of their pupils either on a general level or in
ls
a specific field of study. Identify and analyse popular
oe

quiz shows and write a Python program to create a quiz


that should also contain the following functionalities
kg

besides the one identified by you as a result of


your analysis.
.d

• Create an administrative user ID and password to


w

categorically add or modify delete a question.


w

• Register the student before allowing her/him to


//w

play a quiz.
• Allow selection of category based on subject area.
s:

• Display questions as per the chosen category.


tp

• Keep the score as the participant plays.


ht

• Display final score.


3. Our heritage monuments are our assets. They are
a reflection of our rich and glorious past and an
inspiration for our future. UNESCO has identified some
of Indian heritage sites as World Heritage sites. Collect
the following information about these sites:
• What is the name of the site?
• Where is it located?
▪ District
▪ State

2020-21

Chap 4.indd 79
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com

80 InformatIcs PractIces – class XI

notes • When was it built?


• Who built it?
• Why was it built?
• Website link (if any)
Write a Python program to:
• Create an administrative user ID and password to
add, modify or delete an entered heritage site in the
list of sites.
• Display the list of world heritage sites in India.
• Search and display information of a world heritage
site entered by the user.

om
• Display the name(s) of world heritage site(s) on the
basis of the state input by the user.

.c
ns
io
ut
ol
ls
oe
kg
.d
w
w
//w
s:
tp
ht

2020-21

Chap 4.indd 80
Downloaded from https:// www.studiestoday.com
Downloaded from https:// www.dkgoelsolutions.com 19-Jul-19 3:31:21 PM

You might also like