SlideShare a Scribd company logo
LIST IN PYTHON
Mutable data type
List and Dictionary in Python (Syllabus)
Lists: list operations - creating, initializing, traversing and
manipulating lists, list methods and built-in functions.
len(), list(), append(), extend(), insert(), count(), index()
remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum()
Dictionary: concept of key-value pair, creating, initializing,
traversing, updating and deleting elements, dictionary methods
and built-in functions.
len(), dict(), keys(), values(), items(), get(), update(), clear(),
del()
1
Sangita Panchal
• A list is a sequence of comma separated values (elements/objects) enclosed
in square brackets [].
• The values in a list may be of different types (integer, float, string, list, tuple
etc.) – Heterogeneous data type.
• Lists are mutable i.e. values in a list can be edited /changed.
Sangita Panchal
List – Creating and Initializing list
L1 = [] #Empty list
L1 = [‘English’, 45, ‘Maths’, 86, ‘Rajesh’, 1234]
L2 = [12, 15, ‘Manish’, [45, 87], 23] #Nested List
L3 = [‘Sonia’, (‘E001’, ‘D001’), 34000] # Tuple within a list
L = [1,"abc",(23,12),[23,"str"],{1:"A",2:"B"}]
# number, string, tuple, list, dict
2
List items can be accessed by using their index or indices
Sangita Panchal
Accessing List by Index
Forward
Index
Backward
Index
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[3])
print(L[1+4])
print(L[2*2])
print(L[5-4+1])
97
89
Sc.
Maths
3
Slicing
[ start index : end index : step ]
The default of start index is 0, step is 1. It will display data from
start index to end-1 index.
Sangita Panchal
Accessing List - Slicing
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L[ :4])
print(L[2: ])
print(L[ : ])
print(L[ : :-1])
['Eng', 65, 'Maths', 97]
['Maths', 97, 'Sc.', 89]
['Eng', 65, 'Maths', 97, 'Sc.', 89]
[89, 'Sc.', 97, 'Maths', 65, 'Eng']
4
Sangita Panchal
Change data in the list
L = ["Eng",65,"Maths",97, "Sc.",89]
print(L)
L[1] = 90
print(L)
L[2:4] = ['IP',99]
print(L)
L[1:3] = [ ]
print(L)
['Eng’, 65, 'Maths', 97, 'Sc.', 89]
['Eng', 90, 'Maths', 97, 'Sc.', 89]
['Eng', 90, 'IP', 99, 'Sc.', 89]
['Eng', 99, 'Sc.', 89]
5
Sangita Panchal
List operations – Concatenation
A = [12, 43]
B = [34, 78]
C = A + B
print("C = ",C)
A = A + B
print("A = ",A)
B += A
print("B = ",B)
C = [12, 43, 34, 78]
A = [12, 43, 34, 78]
B = [34, 78, 12, 43, 34, 78]
A = [12, 43]
A = A + 5
TypeError: can only
concatenate list (not "int")
to list
Concatenation: It takes ‘+’ operator to concatenate with another list.
6
Correct
A = [12,43]
A = A + [5]
Sangita Panchal
List operations – Repetition
L = [12, 43]
print(L * 2)
L1 = [1,"Amit"]
print(3 * L1)
[12, 43, 12, 43]
[1, 'Amit', 1, 'Amit', 1, 'Amit']]
L = [12, 43]
L2 = [3]
print(L * L2)
TypeError: can't multiply
sequence by non-int value
Repetition: It takes ‘*’ operator to repeat the list content by the
given number.
7
Sangita Panchal
List operations –Membership
L = [12, 43]
L1 = [1,"Amit"]
print("Amit" in L1)
print(12 not in L)
True
False
Membership: It check whether the given element is present in
the list or not. It uses
in : The given element is present.
not in: The given element is not present.
8
Sangita Panchal
Traversing a List
L = [12,"Amit",[23,43,29]]
for i in L:
print(i, end = " ")
print()
for i in range(len(L)):
print(L[i],end = " ")
12 Amit [23, 43, 29]
12 Amit [23, 43, 29]
9
There are two ways to traverse the list.
1. Element / Member
2. Index – 0, 1, …len(L) - 1
Sangita Panchal
Traversing a List – To add number five to each element in
the list.
L = [12, 43, 17, 34, 29]
print("Initial list is: ", L)
print("After adding 5: ", end = "")
for i in range(len(L)):
L[i] += 5
print(L)
Initial list is: [12, 43, 17, 34, 29]
After adding 5: [17, 48, 22, 39, 34]
10
Sangita Panchal
List methods – len(), append(), extend()
L = [14,32,29]
L1 = [22,25]
print(L,len(L))
L.append(L1)
print(“After append”,L,len(L))
L = [14,32,29]
print(L,len(L))
L1 = [22,25]
L.extend(L1)
print(“After extend”,L,len(L))
[14, 32, 29] 3
After append [14, 32, 29, [22, 25]] 4
[14, 32, 29] 3
After extend [14, 32, 29, 22, 25] 5
11
append(): It adds the object as one element.
extend(): It adds the elements in the object as
individual element in the list.
Sangita Panchal
List methods – count(),insert(),remove()
L = [14,32,29,28,32,14,28]
print(L)
print("Count of 14: ",L.count(14))
L.insert(3,14)
print(L)
print("Count of 14: ",L.count(14))
L.remove(14)
L.remove(14)
print(L)
print("Count of 14: ",L.count(14))
[14, 32, 29, 28, 32, 14, 28]
Count of 14: 2
[14, 32, 29, 14, 28, 32, 14, 28]
Count of 14: 3
[32, 29, 28, 32, 14, 28]
Count of 14
12
count(): It counts the given data present in the list.
insert(): It inserts the data at a given location in the list.
remove(): It removes the given data in a list, whichever comes first from the left to right.
Sangita Panchal
List methods – reverse(), sort()
L = [14,32,29,28,12,24]
print(L)
L.reverse()
print("List in reverse order:",L)
L.sort()
print("List in ascending order:",L)
L.sort(reverse = True)
print("List in descending order:",L)
[14, 32, 29, 28, 12, 24]
List in reverse order:
[24, 12, 28, 29, 32, 14]
List in ascending order:
[12, 14, 24, 28, 29, 32]
List in descending order:
[32, 29, 28, 24, 14, 12]
reverse(): it reverses the member in the list.
sort(): It sorts the data in the list in ascending order.
sort(reverse = True): it sorts the data in the list in descending order.
Note: In sort(), it works with homogeneous data type.
13
Sangita Panchal
List methods – sort() in string data type
L = ["Zen","Ben","Arif","Kity"]
print("Original list", L,sep = ‘n’)
L.sort()
print("List in Ascending order",L,sep = ‘n’)
L.sort(reverse = True)
print("List in Descending order",L,sep = ‘n’)
Original list
['Zen', 'Ben', 'Arif', 'Kity']
List in Ascending order
['Arif', 'Ben', 'Kity', 'Zen']
List in Descending order
['Zen', 'Kity', 'Ben', 'Arif']
14
Sangita Panchal
List methods – sort() in nested list
L = [[23,12],[34,45],[22,11]]
print("Original list", L,sep = ‘n’))
L.sort()
print("List in Ascending order",L,sep = ‘n’)
L.sort(reverse = True)
print("List in Descending order",L,sep = ‘n’))
Original list
[[23, 12], [34, 45], [22, 11]]
List in Ascending order
[[22, 11], [23, 12], [34, 45]]
List in Descending order
[[34, 45], [23, 12], [22, 11]]
15
Sangita Panchal
List methods – sort() vs sorted
L = [12,9,5,2,3]
print("Original list", L)
L1 = sorted(L)
print("List in Ascending order",L1)
L1 = sorted(L,reverse = True)
print("List in Descending order",L1)
Original list [12, 9, 5, 2, 3]
List in Ascending order [2, 3, 5, 9, 12]
List in Descending order [12, 9, 5, 3, 2]
16
Sangita Panchal
List methods – sort() vs sorted
L = ["Zen","Ben","Arif","Kity"]
print("Original list", L, sep = ‘n’)
L1 = sorted(L)
print("List in Ascending order",L1,sep = ‘n’)
L1 = sorted(L,reverse = True)
print("List in Descending order",L1,sep = ‘n’)
17
Original list
['Zen', 'Ben', 'Arif', 'Kity']
List in Ascending order
['Arif', 'Ben', 'Kity', 'Zen']
List in Descending order
['Zen', 'Kity', 'Ben', 'Arif']
Sangita Panchal
List methods – pop(), del
L = [14,32,29,28,12,24]
print(L)
print("Remove the -1 index value:“)
L.pop() ; print(L)
print("Remove the 2 index value:“)
L.pop(2) ; print(L)
print("Remove the 1 index value:“
del L[1] ; print(L)
print("Delete the entire list")
del L ; print(L)
[14, 32, 29, 28, 12, 24]
Remove the -1 index value:
24
[14, 32, 29, 28, 12]
Remove the 2 index value:
29
[14, 32, 28, 12]
Remove the 1 index value:
[14, 28, 12]
Delete the entire list
NameError: name 'L' is not defined12]
18
pop(): It deletes the element mentioned as index. The default index is -1.
del : It deletes the element mentioned as index, otherwise it deletes the entire list
permanently.
Sangita Panchal
List methods – index()
L = [14,32,29,32,12,24]
print(L)
print("Index of 32 from left",end ="")
print(L.index(32))
print("Index of 32 after index 2",end ="")
print(L.index(32,2))
print("Index of 40 not present",end ="")
print(L.index(40))
[14, 32, 29, 32, 12, 24]
Index of 32 from left 1
Index of 32 after index 2 3
Index of 40 not present
ValueError: 40 is not in list
19
Sangita Panchal
List built-in functions – min(),max(),sum()
L = [14,32,29,32,12,24]
print(L)
print("Maximum:",max(L))
print("Minimum:",min(L))
print("Sum:",sum(L))
print("Average:",round(sum(L)/len(L),2))
[14, 32, 29, 32, 12, 24]
Maximum: 32
Minimum: 12
Sum: 143
Average: 23.83
20
max(): It returns the maximum value in the list.
min(): it returns the minimum value in the list.
sum(): it returns the sum of all the values in the list.
Note: min(), max() works with number or string data type.
sum() works with number data type only.
Sangita Panchal
Program 1: To input how many marks, enter marks and
display the average mark.
n = int(input("Enter no. of marks"))
L = []
for i in range(n):
marks = int(input("Enter marks"))
L.append(marks)
s = 0
for i in L:
s += i
print("Average mark", s/n)
Enter no. of marks5
Enter marks23
Enter marks19
Enter marks22
Enter marks15
Enter marks20
Average mark 19.8
21
Sangita Panchal
Program 2: To input number of marks, enter marks, search whether
the given mark is present at location or not.
L = []
n = int(input("How many numbers"))
for i in range(n):
n = int(input("Enter number"))
L.append(n)
num = int(input("Enter the number
to be searched: "))
pos = -1
for i in range(n):
if L[i] == num: pos = i ; break
if pos == -1 : print("Number",num,"is not present")
else: print("Number",num,"is present at",pos, "position")
How many numbers5
Enter number21
Enter number23
Enter number20
Enter number17
Enter number19
Enter the number to be searched: 20
Number 20 is present at 2 position
22
Sangita Panchal
Program 3: A menu driven program of list, to do the following:
1. Add a data
2. Insert a data
3. Add list
4. Modify data by index
5. Delete by value
6. Delete by position
7. Sort in ascending order
8. Sort in descending order
9. display list
23
Sangita Panchal
L = []
while True:
print("""1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display""")
choice = int(input("Enter the choice"))
if choice == 1:
n = int(input("Enter data"))
L.append(n) ; print(L)
elif choice == 2:
n = int(input("Enter data"))
pos = int(input("Enter position"))
L.insert(pos,n) ; print(L)
elif choice == 3:
nList = eval(input("Enter the list to be appended: "))
L.extend(nList) ; print(L)
24
Sangita Panchal
elif choice == 4:
i = int(input("Enter the data position to modified: "))
if i < len(L):
num = eval(input("Enter the new element: "))
L[i] = num
else:
print("Position not in the list")
print(L)
elif choice == 5:
i = int(input("Enter the element position to be deleted: "))
if i < len(L):
num = L.pop(i)
else:
print("nPosition not in the list")
print(L)
25
Sangita Panchal
elif choice == 6:
num = int(input("nEnter the element to be deleted: "))
if num in L:
L.remove(num)
else:
print("nElement",element,"is not present in the list")
elif choice == 7:
L.sort()
elif choice == 8:
L.sort(reverse = True)
elif choice == 9:
print("nThe list is:", L)
else:
print("Exit")
break
26
Sangita Panchal
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice1
Enter data18
[18]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice2
Enter data23
Enter position0
[23, 18]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
Enter the choice3
Enter the list to be appended: 25,21,20
[23, 18, 25, 21, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice4
Enter the data position to modified: 2
Enter the new element: 15
[23, 18, 15, 21, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice5
Enter the element position to be deleted: 1
[23, 15, 21, 20]
27
Sangita Panchal
28
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice6
Enter the element to be deleted: 21
[23, 15, 20]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice7
[15, 20, 23]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice8
[23, 20, 15]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice9
The list is: [23, 20, 15]
1 append, 2 insert, 3 append list,
4 - modify, 5 - Delete by position,
6 - Delete by value, 7 - sort in ascending
8 - Sort in descending, 9- Display
Enter the choice10
Exit
DICTIONARY IN
PYTHON
Mutable data type
Sangita Panchal
Dictionary in Python
A dictionary is a mutable object that can store any number of Python
objects. It falls under mapping – a mapping between a set of keys
with corresponding values.
 The items are separated by comma and the entire dictionary is
enclosed in curly braces.
 Each item consists of two parts – key and a value, separated by a
colon (:).
 Keys are unique in dictionary. They must be of an immutable data
types such as strings, numbers or tuples.
 The values may have duplicate values. They can be of any data
type.
30
Sangita Panchal
Dictionary in Python
D1 = {'Ani': 12, 'John':32}
D2 = {('Mia', 45, 32): [56, 23, 23, 66, 77]}
D3 = {1:'Ginni', 2:'Anuj'}
D4 = { 1: ('Mrinal', 65), 2: ('Sia', 89)}
print(D1);print(D2)
print(D3);print(D4)
D5 = {[‘Ani’ , ’John’]: [12, 32 ]}
print(D5)
{'Ani': 12, 'John': 32}
{('Mia', 45, 32): [56, 23, 23, 66, 77]}
{1: 'Ginni', 2: 'Anuj'}
{1: ('Mrinal', 65), 2: ('Sia', 89)}
TypeError: unhashable type: 'list'
31
Sangita Panchal
Creating an Empty Dictionary
D = {}
print("D = ",D)
D1 = dict()
print("D1 = ",D1)
Two ways to create an empty dictionary
D = {}
D1 = {}
32
Sangita Panchal
Accessing Items in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
print("The value of Joe:",D['Joe'])
print("The value of Amit:" D['Amit'])
The items of the dictionary are accessed via the keys rather than
the index. Each key treated as an index and map with the value.
{'Amit': 56, 'Joe': 32}
The value of Joe: 32
The value of Amit: 56
33
Sangita Panchal
Membership operation in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
print("Check for Amit:",'Amit' in D)
print("Check for Seema:",'Seema' in D)
print("Check of Joe not present",'Joe' not in D)
The membership operator (in) checks whether the key is present in
a dictionary or not. It returns True or False.
{'Amit': 56, 'Joe': 32}
Check for Amit: True
Check for Seema: False
Check of Joe not present False
34
Sangita Panchal
Adding /Modifying the item in a Dictionary
D = {'Amit':56,'Joe':32}
print(D)
D['Amit'] = 100
D['Seema'] = 78
print("The updated dictionary")
print(D)
As dictionary is mutable, you can add an item or modify the value
of an already existing key in a dictionary.
{'Amit': 56, 'Joe': 32}
The updated dictionary
{'Amit': 100, 'Joe': 32, 'Seema': 78}
35
Sangita Panchal
Traversing a Dictionary
D = {'Amit':56,'Joe':32,'Sid':45}
for key in D:
print(key,":",D[key])
You can traverse a dictionary using for loop. There are two ways to
do the traversing.
Amit : 56
Joe : 32
Sid : 45
D = {'Amit':56,'Joe':32,'Sid':45}
for key,value in D.items():
print(key,":",value)
Amit : 56
Joe : 32
Sid : 45
36
Sangita Panchal
Built-in functions and methods in Dictionary – len(), update()
D = dict() ; print(D,len(D))
D1 = {'Amit':56,'Joe':32,'Sid':45}
D.update(D1)
print(D,len(D))
D2 = {'Joe':43,'Jia':47}
D.update(D2) ; print(D,len(D))
{} 0
{'Amit': 56, 'Joe': 32, 'Sid': 45} 3
{'Amit': 56, 'Joe': 43, 'Sid': 45, 'Jia': 47} 4
dict(): It creates and empty dictionary.
len(): It returns the number of items in the dictionary.
update(): If key is present, it updates the value, otherwise, adds the
item in the dictionary.
37
Sangita Panchal
Built-in functions and methods in Dictionary –
keys(),values(),items()
D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47}
print(D.keys())
print(D.values())
print(D.items())
dict_keys(['Amit', 'Joe', 'Sid', 'Jia'])
dict_values([56, 32, 45, 47])
dict_items([('Amit', 56), ('Joe', 32), ('Sid', 45), ('Jia', 47)])
keys(): It returns the list of keys in the dictionary.
values(): it returns the list of values in the dictionary.
items(): It returns the key, value pair in tuple and entire data in list.
38
Sangita Panchal
Built-in functions and methods in Dictionary – get()
D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47}
D = {'Amit':56,'Joe':32,'Sid':45}
print(D.get('Sid'))
print(D.get('amit'))
print(D['Sid'])
print(D['amit'])
45
None
45
KeyError: 'amit'
It returns the value corresponding to the passed key, if present;
otherwise it returns None. It is similar to D[key].
39
Sangita Panchal
Built-in functions and methods in Dictionary – get()
D = {'Amit':56,'Joe':32,'Sid':45}
del D['Joe']
print(“Aafter deleting Joe“, D)
D.clear()
print(“After deleting content“,D)
del D
print("Permanently deletes the
dictionary“,D)
After deleting Joe {'Amit': 56, 'Sid': 45}
After deleting content {}
Permanently deletes the dictionary
NameError: name 'D' is not defined'
clear(): deletes the entire content leaving empty dict.
del: deletes the specified item or entire dict permanently.
40
Sangita Panchal
Write a python program to create a dictionary from a string.
Sample string ‘w3resource’
Expected output {‘3’:1, ‘s’:1, ‘r’:2, ‘u’:1, ‘w’:1, ‘c’:1, ‘e’:2, ‘o’:1}
st = input("Enter a string ")
d = {}
for ch in st:
if ch in d:
d[ch] += 1
else:
d[ch] = 1
print(d)
Enter a string AEOBCAB
{'A': 2, 'E': 1, 'O': 1, 'B': 2, 'C': 1}
41
Sangita Panchal
Write a program to convert a number entered by the user into its
corresponding number in words. For example, if the number is 876,
then the output should be ‘Eight Seven Six’
num = input("Enter any number")
d = {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)
value = d[key]
result = result + " " +value
print( result)
Enter any number17439
One Seven Four Three Nine
42
Sangita Panchal
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:
 Display the name and phone number for all your friends.
 Add a new key-value pair in this dictionary and display the
modified dictionary.
 Enter the name whose phone number you want to modify. Display
the modified dictionary.
 Enter the friend’s name and check if a friend is present in the
dictionary or not.
 Display the dictionary in sorted order of names.
43
Sangita Panchal
D = {}
while True:
print("1 create/add, 2 modify, 3 search, 4 sort, 5 exit")
choice = int(input("Enter choice"))
if choice == 1:
while True:
name = input("Enter your name ")
phone = input("Enter your phone number")
D[name] = phone
choice = input("Continue Y/N")
if choice.upper() == "N":
break
print(D)
44
Sangita Panchal
elif choice == 2:
n = input("Enter the name whose phone number
you want to modified")
flag = 0
for i in D.keys():
if i == n:
p = input("Enter the modified phone number")
D[i] = p ; flag = 1 ; break
if flag == 0: print("Name not found")
print("The dictionary is = ", D)
45
Sangita Panchal
elif choice == 3:
n = input("Name")
flag = 0
for i in D.keys():
if i == n: print("Present") ; flag = 1 ; break
if flag == 0: print("Name Not present")
elif choice == 4:
for key,value in sorted(D.items()):
print(key,":",value,end = ",")
elif choice == 5: print("End of program");break
else: print("Enter correct choice")
46
Sangita Panchal
47
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice1
Enter your name samy
Enter your phone number2134
Continue Y/Ny
Enter your name joe
Enter your phone number4343
Continue Y/Nn
{'samy': '2134', 'joe': '4343'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice2
Enter the name whose phone number you want to modifiedjoe
Enter the modified phone number1111
The dictionary is = {'samy': '2134', 'joe': '1111'}
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice3
Namesamy
Present
1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice4
joe : 1111,samy : 2134,1 create/add, 2 modify, 3 search, 4 sort, 5 exit
Enter choice5
End of program
List and Dictionary in python

More Related Content

What's hot (20)

PPTX
List in Python
Sharath Ankrajegowda
 
PDF
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
PPTX
Data Structures in Python
Devashish Kumar
 
PPTX
Linked list in Data Structure and Algorithm
KristinaBorooah
 
PPT
Stack
srihariyenduri
 
PPTX
Searching and sorting
PoojithaBollikonda
 
PPT
Singly link list
Rojin Khadka
 
PPTX
This pointer
Kamal Acharya
 
PDF
Python exception handling
Mohammed Sikander
 
PPTX
File Handling Python
Akhil Kaushik
 
PPTX
DataFrame in Python Pandas
Sangita Panchal
 
PPT
Expression evaluation
JeeSa Sultana
 
PDF
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
PPT
Stacks
Malainine Zaid
 
PPT
Lec 17 heap data structure
Sajid Marwat
 
PPTX
Presentation on queue
Rojan Pariyar
 
PDF
Python strings
Mohammed Sikander
 
PDF
Tuples in Python
DPS Ranipur Haridwar UK
 
PPT
Stacks
sweta dargad
 
List in Python
Sharath Ankrajegowda
 
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Data Structures in Python
Devashish Kumar
 
Linked list in Data Structure and Algorithm
KristinaBorooah
 
Searching and sorting
PoojithaBollikonda
 
Singly link list
Rojin Khadka
 
This pointer
Kamal Acharya
 
Python exception handling
Mohammed Sikander
 
File Handling Python
Akhil Kaushik
 
DataFrame in Python Pandas
Sangita Panchal
 
Expression evaluation
JeeSa Sultana
 
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Lec 17 heap data structure
Sajid Marwat
 
Presentation on queue
Rojan Pariyar
 
Python strings
Mohammed Sikander
 
Tuples in Python
DPS Ranipur Haridwar UK
 
Stacks
sweta dargad
 

Similar to List and Dictionary in python (20)

PPTX
Data structures: linear lists
ToniyaP1
 
PDF
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
PDF
Python lists &amp; sets
Aswini Dharmaraj
 
PPTX
Lecture2.pptx
Sakith1
 
PDF
Lecture-5.pdf
Bhavya103897
 
PPTX
Unit 4 python -list methods
narmadhakin
 
PPTX
Unit 4.pptx python list tuples dictionary
shakthi10
 
PDF
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
PDF
python_avw - Unit-03.pdf
AshaWankar1
 
PDF
List,tuple,dictionary
nitamhaske
 
PPTX
Python-List.pptx
AnitaDevi158873
 
PPTX
listppt.pptx h4wtgesvzdfvgsrbyhrrtgsvefcdef
rajpalyadav13052024
 
PDF
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
PPTX
List_tuple_dictionary.pptx
ChandanVatsa2
 
PPTX
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
usha raj
 
PPTX
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
meganathan162007
 
PPTX
Abstract Algebra and Category Theory
Naveenkumar Muguda
 
PPTX
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
DeepakRattan3
 
PDF
Session -5for students.pdf
priyanshusoni53
 
PPTX
Python _dataStructures_ List, Tuples, its functions
VidhyaB10
 
Data structures: linear lists
ToniyaP1
 
GE3151_PSPP_UNIT_4_Notes
Guru Nanak Technical Institutions
 
Python lists &amp; sets
Aswini Dharmaraj
 
Lecture2.pptx
Sakith1
 
Lecture-5.pdf
Bhavya103897
 
Unit 4 python -list methods
narmadhakin
 
Unit 4.pptx python list tuples dictionary
shakthi10
 
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
python_avw - Unit-03.pdf
AshaWankar1
 
List,tuple,dictionary
nitamhaske
 
Python-List.pptx
AnitaDevi158873
 
listppt.pptx h4wtgesvzdfvgsrbyhrrtgsvefcdef
rajpalyadav13052024
 
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
List_tuple_dictionary.pptx
ChandanVatsa2
 
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
usha raj
 
listtupledictionary-2001okdhfuihcasbdjj02082611.pptx
meganathan162007
 
Abstract Algebra and Category Theory
Naveenkumar Muguda
 
PYTHON-PROGRAMMING-UNIT-III.pptx kghbg kfhjf jruufg jtuuf
DeepakRattan3
 
Session -5for students.pdf
priyanshusoni53
 
Python _dataStructures_ List, Tuples, its functions
VidhyaB10
 
Ad

Recently uploaded (20)

PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PDF
Horarios de distribución de agua en julio
pegazohn1978
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Horarios de distribución de agua en julio
pegazohn1978
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
epi editorial commitee meeting presentation
MIPLM
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Ad

List and Dictionary in python

  • 2. List and Dictionary in Python (Syllabus) Lists: list operations - creating, initializing, traversing and manipulating lists, list methods and built-in functions. len(), list(), append(), extend(), insert(), count(), index() remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum() Dictionary: concept of key-value pair, creating, initializing, traversing, updating and deleting elements, dictionary methods and built-in functions. len(), dict(), keys(), values(), items(), get(), update(), clear(), del() 1 Sangita Panchal
  • 3. • A list is a sequence of comma separated values (elements/objects) enclosed in square brackets []. • The values in a list may be of different types (integer, float, string, list, tuple etc.) – Heterogeneous data type. • Lists are mutable i.e. values in a list can be edited /changed. Sangita Panchal List – Creating and Initializing list L1 = [] #Empty list L1 = [‘English’, 45, ‘Maths’, 86, ‘Rajesh’, 1234] L2 = [12, 15, ‘Manish’, [45, 87], 23] #Nested List L3 = [‘Sonia’, (‘E001’, ‘D001’), 34000] # Tuple within a list L = [1,"abc",(23,12),[23,"str"],{1:"A",2:"B"}] # number, string, tuple, list, dict 2
  • 4. List items can be accessed by using their index or indices Sangita Panchal Accessing List by Index Forward Index Backward Index L = ["Eng",65,"Maths",97, "Sc.",89] print(L[3]) print(L[1+4]) print(L[2*2]) print(L[5-4+1]) 97 89 Sc. Maths 3
  • 5. Slicing [ start index : end index : step ] The default of start index is 0, step is 1. It will display data from start index to end-1 index. Sangita Panchal Accessing List - Slicing L = ["Eng",65,"Maths",97, "Sc.",89] print(L[ :4]) print(L[2: ]) print(L[ : ]) print(L[ : :-1]) ['Eng', 65, 'Maths', 97] ['Maths', 97, 'Sc.', 89] ['Eng', 65, 'Maths', 97, 'Sc.', 89] [89, 'Sc.', 97, 'Maths', 65, 'Eng'] 4
  • 6. Sangita Panchal Change data in the list L = ["Eng",65,"Maths",97, "Sc.",89] print(L) L[1] = 90 print(L) L[2:4] = ['IP',99] print(L) L[1:3] = [ ] print(L) ['Eng’, 65, 'Maths', 97, 'Sc.', 89] ['Eng', 90, 'Maths', 97, 'Sc.', 89] ['Eng', 90, 'IP', 99, 'Sc.', 89] ['Eng', 99, 'Sc.', 89] 5
  • 7. Sangita Panchal List operations – Concatenation A = [12, 43] B = [34, 78] C = A + B print("C = ",C) A = A + B print("A = ",A) B += A print("B = ",B) C = [12, 43, 34, 78] A = [12, 43, 34, 78] B = [34, 78, 12, 43, 34, 78] A = [12, 43] A = A + 5 TypeError: can only concatenate list (not "int") to list Concatenation: It takes ‘+’ operator to concatenate with another list. 6 Correct A = [12,43] A = A + [5]
  • 8. Sangita Panchal List operations – Repetition L = [12, 43] print(L * 2) L1 = [1,"Amit"] print(3 * L1) [12, 43, 12, 43] [1, 'Amit', 1, 'Amit', 1, 'Amit']] L = [12, 43] L2 = [3] print(L * L2) TypeError: can't multiply sequence by non-int value Repetition: It takes ‘*’ operator to repeat the list content by the given number. 7
  • 9. Sangita Panchal List operations –Membership L = [12, 43] L1 = [1,"Amit"] print("Amit" in L1) print(12 not in L) True False Membership: It check whether the given element is present in the list or not. It uses in : The given element is present. not in: The given element is not present. 8
  • 10. Sangita Panchal Traversing a List L = [12,"Amit",[23,43,29]] for i in L: print(i, end = " ") print() for i in range(len(L)): print(L[i],end = " ") 12 Amit [23, 43, 29] 12 Amit [23, 43, 29] 9 There are two ways to traverse the list. 1. Element / Member 2. Index – 0, 1, …len(L) - 1
  • 11. Sangita Panchal Traversing a List – To add number five to each element in the list. L = [12, 43, 17, 34, 29] print("Initial list is: ", L) print("After adding 5: ", end = "") for i in range(len(L)): L[i] += 5 print(L) Initial list is: [12, 43, 17, 34, 29] After adding 5: [17, 48, 22, 39, 34] 10
  • 12. Sangita Panchal List methods – len(), append(), extend() L = [14,32,29] L1 = [22,25] print(L,len(L)) L.append(L1) print(“After append”,L,len(L)) L = [14,32,29] print(L,len(L)) L1 = [22,25] L.extend(L1) print(“After extend”,L,len(L)) [14, 32, 29] 3 After append [14, 32, 29, [22, 25]] 4 [14, 32, 29] 3 After extend [14, 32, 29, 22, 25] 5 11 append(): It adds the object as one element. extend(): It adds the elements in the object as individual element in the list.
  • 13. Sangita Panchal List methods – count(),insert(),remove() L = [14,32,29,28,32,14,28] print(L) print("Count of 14: ",L.count(14)) L.insert(3,14) print(L) print("Count of 14: ",L.count(14)) L.remove(14) L.remove(14) print(L) print("Count of 14: ",L.count(14)) [14, 32, 29, 28, 32, 14, 28] Count of 14: 2 [14, 32, 29, 14, 28, 32, 14, 28] Count of 14: 3 [32, 29, 28, 32, 14, 28] Count of 14 12 count(): It counts the given data present in the list. insert(): It inserts the data at a given location in the list. remove(): It removes the given data in a list, whichever comes first from the left to right.
  • 14. Sangita Panchal List methods – reverse(), sort() L = [14,32,29,28,12,24] print(L) L.reverse() print("List in reverse order:",L) L.sort() print("List in ascending order:",L) L.sort(reverse = True) print("List in descending order:",L) [14, 32, 29, 28, 12, 24] List in reverse order: [24, 12, 28, 29, 32, 14] List in ascending order: [12, 14, 24, 28, 29, 32] List in descending order: [32, 29, 28, 24, 14, 12] reverse(): it reverses the member in the list. sort(): It sorts the data in the list in ascending order. sort(reverse = True): it sorts the data in the list in descending order. Note: In sort(), it works with homogeneous data type. 13
  • 15. Sangita Panchal List methods – sort() in string data type L = ["Zen","Ben","Arif","Kity"] print("Original list", L,sep = ‘n’) L.sort() print("List in Ascending order",L,sep = ‘n’) L.sort(reverse = True) print("List in Descending order",L,sep = ‘n’) Original list ['Zen', 'Ben', 'Arif', 'Kity'] List in Ascending order ['Arif', 'Ben', 'Kity', 'Zen'] List in Descending order ['Zen', 'Kity', 'Ben', 'Arif'] 14
  • 16. Sangita Panchal List methods – sort() in nested list L = [[23,12],[34,45],[22,11]] print("Original list", L,sep = ‘n’)) L.sort() print("List in Ascending order",L,sep = ‘n’) L.sort(reverse = True) print("List in Descending order",L,sep = ‘n’)) Original list [[23, 12], [34, 45], [22, 11]] List in Ascending order [[22, 11], [23, 12], [34, 45]] List in Descending order [[34, 45], [23, 12], [22, 11]] 15
  • 17. Sangita Panchal List methods – sort() vs sorted L = [12,9,5,2,3] print("Original list", L) L1 = sorted(L) print("List in Ascending order",L1) L1 = sorted(L,reverse = True) print("List in Descending order",L1) Original list [12, 9, 5, 2, 3] List in Ascending order [2, 3, 5, 9, 12] List in Descending order [12, 9, 5, 3, 2] 16
  • 18. Sangita Panchal List methods – sort() vs sorted L = ["Zen","Ben","Arif","Kity"] print("Original list", L, sep = ‘n’) L1 = sorted(L) print("List in Ascending order",L1,sep = ‘n’) L1 = sorted(L,reverse = True) print("List in Descending order",L1,sep = ‘n’) 17 Original list ['Zen', 'Ben', 'Arif', 'Kity'] List in Ascending order ['Arif', 'Ben', 'Kity', 'Zen'] List in Descending order ['Zen', 'Kity', 'Ben', 'Arif']
  • 19. Sangita Panchal List methods – pop(), del L = [14,32,29,28,12,24] print(L) print("Remove the -1 index value:“) L.pop() ; print(L) print("Remove the 2 index value:“) L.pop(2) ; print(L) print("Remove the 1 index value:“ del L[1] ; print(L) print("Delete the entire list") del L ; print(L) [14, 32, 29, 28, 12, 24] Remove the -1 index value: 24 [14, 32, 29, 28, 12] Remove the 2 index value: 29 [14, 32, 28, 12] Remove the 1 index value: [14, 28, 12] Delete the entire list NameError: name 'L' is not defined12] 18 pop(): It deletes the element mentioned as index. The default index is -1. del : It deletes the element mentioned as index, otherwise it deletes the entire list permanently.
  • 20. Sangita Panchal List methods – index() L = [14,32,29,32,12,24] print(L) print("Index of 32 from left",end ="") print(L.index(32)) print("Index of 32 after index 2",end ="") print(L.index(32,2)) print("Index of 40 not present",end ="") print(L.index(40)) [14, 32, 29, 32, 12, 24] Index of 32 from left 1 Index of 32 after index 2 3 Index of 40 not present ValueError: 40 is not in list 19
  • 21. Sangita Panchal List built-in functions – min(),max(),sum() L = [14,32,29,32,12,24] print(L) print("Maximum:",max(L)) print("Minimum:",min(L)) print("Sum:",sum(L)) print("Average:",round(sum(L)/len(L),2)) [14, 32, 29, 32, 12, 24] Maximum: 32 Minimum: 12 Sum: 143 Average: 23.83 20 max(): It returns the maximum value in the list. min(): it returns the minimum value in the list. sum(): it returns the sum of all the values in the list. Note: min(), max() works with number or string data type. sum() works with number data type only.
  • 22. Sangita Panchal Program 1: To input how many marks, enter marks and display the average mark. n = int(input("Enter no. of marks")) L = [] for i in range(n): marks = int(input("Enter marks")) L.append(marks) s = 0 for i in L: s += i print("Average mark", s/n) Enter no. of marks5 Enter marks23 Enter marks19 Enter marks22 Enter marks15 Enter marks20 Average mark 19.8 21
  • 23. Sangita Panchal Program 2: To input number of marks, enter marks, search whether the given mark is present at location or not. L = [] n = int(input("How many numbers")) for i in range(n): n = int(input("Enter number")) L.append(n) num = int(input("Enter the number to be searched: ")) pos = -1 for i in range(n): if L[i] == num: pos = i ; break if pos == -1 : print("Number",num,"is not present") else: print("Number",num,"is present at",pos, "position") How many numbers5 Enter number21 Enter number23 Enter number20 Enter number17 Enter number19 Enter the number to be searched: 20 Number 20 is present at 2 position 22
  • 24. Sangita Panchal Program 3: A menu driven program of list, to do the following: 1. Add a data 2. Insert a data 3. Add list 4. Modify data by index 5. Delete by value 6. Delete by position 7. Sort in ascending order 8. Sort in descending order 9. display list 23
  • 25. Sangita Panchal L = [] while True: print("""1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display""") choice = int(input("Enter the choice")) if choice == 1: n = int(input("Enter data")) L.append(n) ; print(L) elif choice == 2: n = int(input("Enter data")) pos = int(input("Enter position")) L.insert(pos,n) ; print(L) elif choice == 3: nList = eval(input("Enter the list to be appended: ")) L.extend(nList) ; print(L) 24
  • 26. Sangita Panchal elif choice == 4: i = int(input("Enter the data position to modified: ")) if i < len(L): num = eval(input("Enter the new element: ")) L[i] = num else: print("Position not in the list") print(L) elif choice == 5: i = int(input("Enter the element position to be deleted: ")) if i < len(L): num = L.pop(i) else: print("nPosition not in the list") print(L) 25
  • 27. Sangita Panchal elif choice == 6: num = int(input("nEnter the element to be deleted: ")) if num in L: L.remove(num) else: print("nElement",element,"is not present in the list") elif choice == 7: L.sort() elif choice == 8: L.sort(reverse = True) elif choice == 9: print("nThe list is:", L) else: print("Exit") break 26
  • 28. Sangita Panchal 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice1 Enter data18 [18] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice2 Enter data23 Enter position0 [23, 18] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending Enter the choice3 Enter the list to be appended: 25,21,20 [23, 18, 25, 21, 20] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice4 Enter the data position to modified: 2 Enter the new element: 15 [23, 18, 15, 21, 20] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice5 Enter the element position to be deleted: 1 [23, 15, 21, 20] 27
  • 29. Sangita Panchal 28 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice6 Enter the element to be deleted: 21 [23, 15, 20] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice7 [15, 20, 23] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice8 [23, 20, 15] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice9 The list is: [23, 20, 15] 1 append, 2 insert, 3 append list, 4 - modify, 5 - Delete by position, 6 - Delete by value, 7 - sort in ascending 8 - Sort in descending, 9- Display Enter the choice10 Exit
  • 31. Sangita Panchal Dictionary in Python A dictionary is a mutable object that can store any number of Python objects. It falls under mapping – a mapping between a set of keys with corresponding values.  The items are separated by comma and the entire dictionary is enclosed in curly braces.  Each item consists of two parts – key and a value, separated by a colon (:).  Keys are unique in dictionary. They must be of an immutable data types such as strings, numbers or tuples.  The values may have duplicate values. They can be of any data type. 30
  • 32. Sangita Panchal Dictionary in Python D1 = {'Ani': 12, 'John':32} D2 = {('Mia', 45, 32): [56, 23, 23, 66, 77]} D3 = {1:'Ginni', 2:'Anuj'} D4 = { 1: ('Mrinal', 65), 2: ('Sia', 89)} print(D1);print(D2) print(D3);print(D4) D5 = {[‘Ani’ , ’John’]: [12, 32 ]} print(D5) {'Ani': 12, 'John': 32} {('Mia', 45, 32): [56, 23, 23, 66, 77]} {1: 'Ginni', 2: 'Anuj'} {1: ('Mrinal', 65), 2: ('Sia', 89)} TypeError: unhashable type: 'list' 31
  • 33. Sangita Panchal Creating an Empty Dictionary D = {} print("D = ",D) D1 = dict() print("D1 = ",D1) Two ways to create an empty dictionary D = {} D1 = {} 32
  • 34. Sangita Panchal Accessing Items in a Dictionary D = {'Amit':56,'Joe':32} print(D) print("The value of Joe:",D['Joe']) print("The value of Amit:" D['Amit']) The items of the dictionary are accessed via the keys rather than the index. Each key treated as an index and map with the value. {'Amit': 56, 'Joe': 32} The value of Joe: 32 The value of Amit: 56 33
  • 35. Sangita Panchal Membership operation in a Dictionary D = {'Amit':56,'Joe':32} print(D) print("Check for Amit:",'Amit' in D) print("Check for Seema:",'Seema' in D) print("Check of Joe not present",'Joe' not in D) The membership operator (in) checks whether the key is present in a dictionary or not. It returns True or False. {'Amit': 56, 'Joe': 32} Check for Amit: True Check for Seema: False Check of Joe not present False 34
  • 36. Sangita Panchal Adding /Modifying the item in a Dictionary D = {'Amit':56,'Joe':32} print(D) D['Amit'] = 100 D['Seema'] = 78 print("The updated dictionary") print(D) As dictionary is mutable, you can add an item or modify the value of an already existing key in a dictionary. {'Amit': 56, 'Joe': 32} The updated dictionary {'Amit': 100, 'Joe': 32, 'Seema': 78} 35
  • 37. Sangita Panchal Traversing a Dictionary D = {'Amit':56,'Joe':32,'Sid':45} for key in D: print(key,":",D[key]) You can traverse a dictionary using for loop. There are two ways to do the traversing. Amit : 56 Joe : 32 Sid : 45 D = {'Amit':56,'Joe':32,'Sid':45} for key,value in D.items(): print(key,":",value) Amit : 56 Joe : 32 Sid : 45 36
  • 38. Sangita Panchal Built-in functions and methods in Dictionary – len(), update() D = dict() ; print(D,len(D)) D1 = {'Amit':56,'Joe':32,'Sid':45} D.update(D1) print(D,len(D)) D2 = {'Joe':43,'Jia':47} D.update(D2) ; print(D,len(D)) {} 0 {'Amit': 56, 'Joe': 32, 'Sid': 45} 3 {'Amit': 56, 'Joe': 43, 'Sid': 45, 'Jia': 47} 4 dict(): It creates and empty dictionary. len(): It returns the number of items in the dictionary. update(): If key is present, it updates the value, otherwise, adds the item in the dictionary. 37
  • 39. Sangita Panchal Built-in functions and methods in Dictionary – keys(),values(),items() D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47} print(D.keys()) print(D.values()) print(D.items()) dict_keys(['Amit', 'Joe', 'Sid', 'Jia']) dict_values([56, 32, 45, 47]) dict_items([('Amit', 56), ('Joe', 32), ('Sid', 45), ('Jia', 47)]) keys(): It returns the list of keys in the dictionary. values(): it returns the list of values in the dictionary. items(): It returns the key, value pair in tuple and entire data in list. 38
  • 40. Sangita Panchal Built-in functions and methods in Dictionary – get() D = {'Amit':56,'Joe':32,'Sid':45,'Jia':47} D = {'Amit':56,'Joe':32,'Sid':45} print(D.get('Sid')) print(D.get('amit')) print(D['Sid']) print(D['amit']) 45 None 45 KeyError: 'amit' It returns the value corresponding to the passed key, if present; otherwise it returns None. It is similar to D[key]. 39
  • 41. Sangita Panchal Built-in functions and methods in Dictionary – get() D = {'Amit':56,'Joe':32,'Sid':45} del D['Joe'] print(“Aafter deleting Joe“, D) D.clear() print(“After deleting content“,D) del D print("Permanently deletes the dictionary“,D) After deleting Joe {'Amit': 56, 'Sid': 45} After deleting content {} Permanently deletes the dictionary NameError: name 'D' is not defined' clear(): deletes the entire content leaving empty dict. del: deletes the specified item or entire dict permanently. 40
  • 42. Sangita Panchal Write a python program to create a dictionary from a string. Sample string ‘w3resource’ Expected output {‘3’:1, ‘s’:1, ‘r’:2, ‘u’:1, ‘w’:1, ‘c’:1, ‘e’:2, ‘o’:1} st = input("Enter a string ") d = {} for ch in st: if ch in d: d[ch] += 1 else: d[ch] = 1 print(d) Enter a string AEOBCAB {'A': 2, 'E': 1, 'O': 1, 'B': 2, 'C': 1} 41
  • 43. Sangita Panchal Write a program to convert a number entered by the user into its corresponding number in words. For example, if the number is 876, then the output should be ‘Eight Seven Six’ num = input("Enter any number") d = {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) value = d[key] result = result + " " +value print( result) Enter any number17439 One Seven Four Three Nine 42
  • 44. Sangita Panchal 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:  Display the name and phone number for all your friends.  Add a new key-value pair in this dictionary and display the modified dictionary.  Enter the name whose phone number you want to modify. Display the modified dictionary.  Enter the friend’s name and check if a friend is present in the dictionary or not.  Display the dictionary in sorted order of names. 43
  • 45. Sangita Panchal D = {} while True: print("1 create/add, 2 modify, 3 search, 4 sort, 5 exit") choice = int(input("Enter choice")) if choice == 1: while True: name = input("Enter your name ") phone = input("Enter your phone number") D[name] = phone choice = input("Continue Y/N") if choice.upper() == "N": break print(D) 44
  • 46. Sangita Panchal elif choice == 2: n = input("Enter the name whose phone number you want to modified") flag = 0 for i in D.keys(): if i == n: p = input("Enter the modified phone number") D[i] = p ; flag = 1 ; break if flag == 0: print("Name not found") print("The dictionary is = ", D) 45
  • 47. Sangita Panchal elif choice == 3: n = input("Name") flag = 0 for i in D.keys(): if i == n: print("Present") ; flag = 1 ; break if flag == 0: print("Name Not present") elif choice == 4: for key,value in sorted(D.items()): print(key,":",value,end = ",") elif choice == 5: print("End of program");break else: print("Enter correct choice") 46
  • 48. Sangita Panchal 47 1 create/add, 2 modify, 3 search, 4 sort, 5 exit Enter choice1 Enter your name samy Enter your phone number2134 Continue Y/Ny Enter your name joe Enter your phone number4343 Continue Y/Nn {'samy': '2134', 'joe': '4343'} 1 create/add, 2 modify, 3 search, 4 sort, 5 exit Enter choice2 Enter the name whose phone number you want to modifiedjoe Enter the modified phone number1111 The dictionary is = {'samy': '2134', 'joe': '1111'} 1 create/add, 2 modify, 3 search, 4 sort, 5 exit Enter choice3 Namesamy Present 1 create/add, 2 modify, 3 search, 4 sort, 5 exit Enter choice4 joe : 1111,samy : 2134,1 create/add, 2 modify, 3 search, 4 sort, 5 exit Enter choice5 End of program