Tuples Lists Dictionaries
Tuples Lists Dictionaries
CREATING A TUPLE
➢ A Tuple created by enclosing the all the elements inside parenthesis () separated by commas
tuple name=(element1,element2,…….)
• The last tuple contains a string, a float, an integer, list and another tuple
• If a tuple contains another tuple it is known as nested tuple. Here t is a nested tuple.
➢ A Tuple that contains no elements is called the empty tuple.
Eg: b = ()
DISPLAYING A TUPLE
Eg: numbers=(1,2,3,4,5)
print numbers Output: (1,2,3,4,5)
DHANYA V,AP IN IT,CEV 1
Downloaded from Ktunotes.in
ACCESSING TUPLE ELEMENTS
➢ The elemets are accessed by using index numbers. The index start at 0.
➢ The index of first element is 0,second element is 1,third element is 2 and so on.
➢ If tuple contains ‘n’ elements index number varies from 0 to (n-1)
➢ Python allows negative indexes for tuple elements. The negative index starts from -1(last element)
➢ The negative index of last element is -1,second last element is -2, and so on.
Eg1: a=(2,4,8,12)
-ve index -4 -3 -2 -1
+ve Index 0 1 2 3
Element 2 4 8 12
2
Downloaded from Ktunotes.in
Eg2:T1=( “Happy” , 20 , [2,10,1,5] , (44,55) )
print T1 [2] Output: (2,10,1,5)
Print Tl[1] Output :20
Print T1[2] [1] Output:10
Print T1[3] Output (44,55)
Print T1[0][1] Output :a
TUPLE LENGTH
➢ The function len is used to find the length of a TUPLE(number of elements in the TUPLE)
TUPLE TRAVERSAL
3
Downloaded from Ktunotes.in
Eg: a=(11,22,33,44)
Using while loop Using for loop
print a[i]
i=i+1 Easy method
ii)for i in a:
print i
Output: 11
22
33
44
4
Downloaded from Ktunotes.in
TUPLE SLICING
➢A slice is a subset of a tuple .
➢Slice operator (:) is used to extract a slice of the tuple
Syntax: tuple name[n : m : stepsize]
returns the subset of the list from the nth element(including) to the mth element(excluding)
Eg: s=(1,2,3,4,5,6,7,8)
5
Downloaded from Ktunotes.in
➢If you omit the first index (before the colon), the slice starts from beginning of the tuple. If you
omit the second index, the slice goes to the end of the tuple.(+ve step size)
➢If you omit the first index (before the colon), the slice starts from end of the tuple. If you omit
the second index, the slice goes to the beginning of the tuple.(-ve step size)
6
Downloaded from Ktunotes.in
CHANGING A TUPLE
➢ Unlike lists, tuples are immutable.
➢ This means that elements of a tuple cannot be changed . But, if the element is itself a mutable
data type like list, its nested items can be changed.
Eg: x=(1,2,5, [3,8,9] )
x[3][1] =88 Now,x : (1,2,5, [3,88,9] )
DELETING TUPLE ELEMENTS
➢ we can delete an entire tuple
Syntax : del tuple name
Eg: x=(2,5,3,8,9)
del x will delete the entire tuple.
➢ we cannot change or delete the elements in a tuple. But if the element is itself a mutable data
type like list, its nested items can be deleted.
Eg: x=(1,2,5, [3,8,9] )
del x[3][1] Now,x : (1,2,5, [3,9] )
7
Downloaded from Ktunotes.in
TUPLE OPERATIONS
➢ There are 4 basic tuple operations in Python
1. concatenation 2.Repetition 3. in 4. not in
1. concatenation (+)
❑ Joins two tuples
Eg: x=(1,2,3,4)
y=(10,20,30)
z=x + y z: (1,2,3,4,10,20,30)
2.Repetition (*)
❑ This operator replicates the elements in the tuple
Eg: a=(1,2,3)
b=3*a b : (1,2,3,1,2,3,1,2,3)
8
Downloaded from Ktunotes.in
3. in
❑ Used to check whether an element present in a tuple.
❑ Returns true if element is present .Otherwise returns false.
Eg1: X=(2,5,3,8,9)
if(2 in X):
print ”Present”
else:
print”Not Present”
4. not in
❑ Used to check whether an element not present in a tuple
❑ Returns true if element is not present .Otherwise returns false.
Eg: X=(2,5,3,8,9)
if(2 not in X):
print ”Not Present”
else:
print”Present”
DHANYA V,AP IN IT,CEV
9
Downloaded from Ktunotes.in
BUILT IN TUPLE METHODS (FUNCTIONS)
count()
❑ This method is used to count the no.of occurences of an element in a tuple
Syntax: tuplename. count(element)
Eg: a=(1,2,3,4,3,5,1,9,1)
b= a.count(1)
b=3
index()
❑ This method is used to find the lowest index of an element in a tuple
Syntax: tuplename. index(element)
Eg: a=(1,2,3,4,3,5,1,9,1)
b= a.index(3)
b=2
max()
❑ This method is used to find the largest element in a tuple.
Syntax: max(tuple name)
Eg: a= (33,28,99,10)
b=max(a) b:99
min()
❑ This method is used to find the smallest element in a tuple.
Syntax: min(tuple name)
Eg: a= (33,28,99,10)
b=min(a) b:10
DHANYA V,AP IN IT,CEV 10
Downloaded from Ktunotes.in
Sorted()
❑ This method is used to store the sorted elements of a tuple in another tuple
Syntax: tuple1=sorted(tuple2) : By default the elements are stored in asc. order
Eg: a=(“C”, ”Python” ,”Java”)
b=sorted(a)
Then b = (“C”, ”Java” , ”Python”)
❑ For sorting in descending order
Syntax: tuple1=sorted(tuple2,reverse=True)
Eg: a=(“C”, ”Python” ,”Java”)
b=sorted(a, reverse = True)
Then b = (“Python”, ”Java” , ”C”)
11
Downloaded from Ktunotes.in
Advantages of Tuple over List
Since tuples are quite similar to lists, both of them are used in similar situations. However, there are certain
advantages of implementing a tuple over a list. Below listed are some of the main advantages:
• Since tuples are immutable, operations with a tuple is faster than with list.
• Tuples that contain immutable elements can be used as a key for a dictionary. With lists, this is not
possible.
• If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.
Python Program to Swap Two Numbers using Tuple
a= input("Enter the first number :") Largest and smallest element in a set of
b=input("Enter the second number :") numbers using list
print “Before swap: a=", a, "b=",b x = []
(a,b)=(b,a)
n=input(“How many numbers?”)
print“ Afetr Swap: a=",a, "b=",b
print "\nEnter the numbers"
.
READING A STRING FROM KEYBOARD
➢ raw_input() is used in Python2
Eg: s= raw_input(“Enter a string”)
The string entered from keyboard is stored in the variable ‘s’
➢In Python3, input() is used
Eg: s= input(“enter a string”)
➢we can use negative indices, which count backward from the end of the string.
.
3
Downloaded from Ktunotes.in
STRING OPERATORS
1.STRING CONCATENATION
➢+ operator is used
Eg:
s1=“Hello”
s2=“World”
s3=s1+s2
print s3
2.STRING COMPARISON
➢ ==, != , <, <= , > , >= operators are used
. Eg:
s1=raw_input()
s2=raw_input()
if (s1==s2):
print “Equal”
elif(s1<s2):
print “s1 precedes s2”
else:
print”s1 succeeds s2”
DHANYA V,AP IN IT,CEV 4
Downloaded from Ktunotes.in
3.STRING REPLICATION USING * OPERATOR
➢Used to repeat a string for a given no.of times
s=“Hello ”
s2=s*3
print s2
Output : HelloHelloHello
4.IN AND NOT IN OPERATORS
➢Used to check whether a character occurs in a string
s=“Hello ” s=“Hello ”
if(‘e’ in s): if(‘e’ not in s):
print (“Present”) print (“Not Present”)
else: else:
print “Not Present” print “Present”
Output : Present Output : Present
➢Strings are Immutable. Ie we can't change the characters in a string. But we can
delete the entire string
Eg:
greeting = "Hello, world!"
greeting[0] = 'J' # ERROR!
print greeting
6
Downloaded from Ktunotes.in
STRING SLICES
➢A segment(part) of a string is called a slice
➢Slice operator (:) is used to extract a part (slice) of a string
Syntax: string name[n : m : stepsize]
returns the part of the string from the nth character to the mth character, including the first
character but excluding the last
Eg: s= “Program”
1.s[0:5:1] - Progr
.
3.s[2:6:2] - or
4.s[1:4] - rog
DHANYA V,AP IN IT,CEV
5.s[-2:-7:-1] -margo
6.s[-5:-2] -gra 7
Downloaded from Ktunotes.in
➢If you omit the first index (before the colon), the slice starts at the beginning of
the string. If you omit the second index, the slice goes to the end of the string.
1.s[:5:1] - Progr
2.s[:4:] OR s[:4] - Prog
3.s[2::2] - orm
4.s[2::] OR s[2:] - ograms
5.s[::] OR s[:] OR s[::1] - Programs
6.s[::-1] - smargorP
.
8
Downloaded from Ktunotes.in
STRING FUNCTIONS(METHODS)
1.find() method
➢Used to find the index of a given character in the string. If character is not present the
function returns -1 0 1 2 3 4 5
Syntax: string.find(character) P y t h o n
Eg:
s=“Python”
n1=s.find(‘t’) - Output : 2
n2=s.find(‘k’) - Output : -1
➢Also used to search whether a substring is present in a given string. If substring is present it
returns the starting index of substring.If not present the function returns -1
s=“Python”
n1=s.find(‘tho’) - Output : 2 ( starting index of substring)
n2=s.find(‘the’) - Output : -1 (substring not present)
3.replace() method
➢Used to return a copy of a string in which a given substring or character is replaced with
another.
Syntax: string.replace(substring,newsubstring)
string.replace(character, new character)
Eg1 s=“Hello good morning”
s2=s.replace(“morning”,”evening”) - s2: Hello good evening
5.join() method
➢Used to join a list of words by using a delimiter (Eg: hyphen -) and returns a string
Syntax: delimiter.join(list of words)
s2=[ ‘hello’ , ‘World’]
s3= - . join(s2)
Then s3: hello-World (The words are joined by using – and stored in s3)
7.lower() method
➢Used to produce a lowercase copy of the string .
Syntax: string.lower()
s=“HELLO”
s2=s.lower() - s2: hello
8.capitalize() method
➢ Used to produce a copy of the original string and converts the first character of the string to a
capital (uppercase) letter and converts all other characters in to lowercase letters
Eg: s=“hello how are U”
s2=s.capitalize() - s2: Hello how are u
10.max() method
➢Used to return the maximum alphabetical character from a string .
Syntax: max(string)
s=“Hello”
s2=max(s) - s2: o
Ans)
x = raw_input(“Enter a sentence:”)
a= x.split(“ “)
print a
(b) Write a Python program to reverse a string and print whether its palindrome or
not. (8)
Ans)
s= raw_input(“Enter a string”)
s[::-1] means last character to first character ie reverse
s2=s[::-1]
print “Reverse:”,s2
if(s==s2):
print “Palindrome”
else:
print “Not Pal”
if(k==-1):
print”Substring not found”
else:
print “No.of occurrences:”, k
Ans)
s1= raw_input(“Enter first string”)
s1= raw_input(“Enter second string”)
if(s1==s2):
print “Equal”
else:
print “Not”
Ans) i) Hello Wo ii) r iii) dlroW olleH iv) 11 v) rWol vi) llo World
Ans)
Since string is immutable we
s= raw_input(“Enter a string”) cant change original string s.
for k in s: Here we store s in s2 by
if(k=='a' or k=='e' or k=='o'): replacing vowels with null
s2=s.replace(k,"") string
print s2
Ans) Type Error. Because strings are Immutable and we cant modify the individual
characters
Since string is immutable we
one = “This a test”
cant change original string s.
s2=s.replace(‘i’,’u’) Here we store s in s2 by
print s2 replacing ‘i’ with ‘u’
Ans)
s= “mary had a little lamb”
s2=s.replace(“lamb”,”kid”)
k=s.find(“had”)
print k
Let s=”Hai”
s= raw_input(“Enter a string”) last index: 2 (ie len(s)-1)
for i in range(len(s)-1 , -1, -1): first index =0
print s[i], i varies from len(s) to 0 for traverse
in reverse order .
So…for i in range(len(s)-1,-1,-1)
If we need to get index 0 then final
value should be -1.
Step size should be decreased by 1.
Refer Note
print s2
elif(n==2):
c=0
• Here, first we check whether the string
for k in s: contains spaces(space count is stored in c)
if(k==" "): • if no.of spaces in string s =0 it is stored in
c=c+1 another string s2 by adding a ‘$’
if(c==0): character at the start and end by using +
s2='$'+s+'$' operator
• If string s contains spaces it is stored in
else:
another string s2 by replacing spaces with
s2=s.replace(" ","*") *
print s2
s= raw_input(“Enter a string”)
n=len(s)
f=0
for i in range(0,n/2,1):
if(s[i]!= s[n-i-1]):
f=1
break
if(f==0):
print "Palindrome"
else:
print "Not"
➢ List is MUTABLE .Because we can insert ,delete or modify the elements in a list
• The last list contains a string, a float, an integer, and another list
• If a list contains another list it is known as nested list. Here list1 is a nested list.
DHANYA V,AP IN IT,CEV 1
Downloaded from Ktunotes.in
➢ There is a special list that contains no elements. It is called the empty list.
Eg: b = []
CREATING A LIST BY READING ELEMENTS FROM KEYBOARD
x = []
n=input(“enter the no.of elements”)
print "\n Enter the Elements"
for i in range(1,n+1): Inside the for loop ‘n’ numbers are
entered and appended to the list
k=input()
x. append(k)
DISPLAYING A LIST
Syntax: print listname
Eg: x =[1,2,3,4,5]
print x Output: [1,2,3,4,5]
Eg1: a=[2,4,8,12]
-ve index -4 -3 -2 -1
+ve Index 0 1 2 3
Element 2 4 8 12
l=len(num) l=4
l=len(list1) l=3
LIST TRAVERSAL
➢ A lot of computations involve processing a list one element at a time.
➢ We may start at the beginning, select each element in turn, do something to it, and
continue until the end. This pattern of processing is called a traversal.
➢ List Traversal can be done with while or for loops.
for i in s:
print i
Output: Physics
Chemistry
Maths
1.s[:5:1] : [“hello”,11,5,3,4.5]
2.s[:4:] OR s[:4] : [“hello”,11,5,3]
3.s[2::2] : [5,4.5,10]
4.s[2::] OR s[2:] : [5 , 3 , 4.5 , ’x’ ,10 ]
5.s[2::-1] : [5,11,,”Hello”]
5.s[::] OR s[::1] : [“Hello” , 11 , 5 , 3 , 4.5 , ’x’ ,10 ]
6.s[::-1] : [10, ’ x’, 4.5, 3, 5, 11, ”Hello”]
1. concatenation (+)
❑ Joins two lists
Eg: list1=[2,5,3,8,9]
The elements in list1 and
list2=[3,10,20] list2 are combined and
stored in list3
list3=list1+list2 list3= [2,5,3,8,9,3,10,20]
2.Repetition (*)
❑ This operator replicates the elements in the list
The elements in list1 are
Eg: list1=[2,5,8] replicated 3 times and
list2=3*list1 list2=[2,5,8,2,5,8,2,5,8] stored in list2
4. not in
❑ Used to check whether an element not present in a list.
❑ Returns true if element is not present .Otherwise returns false.
Eg: list1=[2,5,3,8,9]
if(2 not in list1):
print ”Not Present”
else:
print”Present”
DHANYA V,AP IN IT,CEV 12
Downloaded from Ktunotes.in
BUILT IN LIST METHODS (FUNCTIONS)
append()
❑ This method is used to add an element to the end of a list
Syntax: listname.append(element)
Eg: a=[1,2,3,4]
a.append(90)
Now a becomes [1,2,3,4,90]
extend()
❑ This method is used to add all the elements of a sequence at the end of a list
Syntax: listname.extend(sequence)
Eg: a=[1,2,3,4] b=[5,6,7]
a.extend(b)
Now a becomes [1,2,3,4,5,6,7]
remove()
❑ This method is used to remove a given element from a list
Syntax: listname. remove(element)
Eg: a=[“C”, ”Python” ,”Java”]
a.remove(“Python”)
Now a becomes : [“C” ,”Java”]
DHANYA V,AP IN IT,CEV 14
Downloaded from Ktunotes.in
pop()
❑ This method is used to remove an element from a given index from a list
❑ If no index is given, it removes the last element.
Syntax: listname. pop(index)
Eg: a=[“C”, ”Python” ,”Java”]
b=a.pop(0) b:”C”
c=a.pop() c:”Java”
count()
❑ This method is used to count the no.of occurences of an element in a list
Syntax: listname. count(element)
Eg: a=[1,2,3,4,3,5,1,9,1]
b= a.count(1) . Then, b=3
reverse()
❑ This method is used to reverses the elements in a list
Syntax: listname. reverse()
Eg: a=[“C”, ”Python” ,”Java”]
a.reverse()
Now a becomes = [“Java”, ”Python” , ”C”]
DHANYA V,AP IN IT,CEV 16
Downloaded from Ktunotes.in
sort()
❑ This method is used to sort the elements in a list
Syntax: listname. sort()
Eg: a=[“C”, ”Python” ,”Java”]
a.sort() Now a becomes = [“C”, ”Java” , ”Python”]
❑ If we need to sort in descending order:
Syntax: listname. sort(reverse=True)
Eg: a=[“C”, ”Python” ,”Java”]
a.sort(reverse=True) Now a becomes = [“Python”, ”Java” , ”C”]
Sorted()
❑ This method is used to store the sorted elements of a list in another list
Syntax: list2=sorted(list1)
Eg: a=[“C”, ”Python” ,”Java”]
b=sorted(a) b= [“C”, ”Java” , ”Python”]
Ans .
List is an ordered collection of elements.Tuple is also an ordered collection of
elements.
Elements can be: numbers , strings, other lists or tuples etc
Difference
1. List is mutable.ie we can change or delete individual elements
Tuple is immutable. individual elements can’t be modified or deleted
x =[]
f=0
The’n’ elements are read one by one in k
n=input(“enter the no.of elements”)
and each element is appended to the list x
print "\nEnter the Elements"
for i in range(1,n+1):
k=input()
x.append(k)
print “List is:” ,x
s=input(“Enter element to be searched”)
for i in range (0,len(x)): elements of the list are accessed by using
index numbers. index number varies from
if (x[i]==s):
0 to listlength-1
print “Found at index:” ,i
f=1
if(f==0):
print “Not Found”
x =[]
f=0
n=input(“enter the no.of elements”)
print "\n Enter the Elements"
for i in range(1,n+1):
k=input()
x.append(k)
print “List is:” ,x
s=input(“Enter element to be searched”)
if s in x: we check whether the search value is
print “Found” present in the list using in operator.
else:
print “Not Found”
Downloaded from Ktunotes.in
x =[]
sum=0
n=input(“enter the no.of elements”)
print "\nEnter the Elements"
for i in range(1,n+1):
k=input()
x.append(k)
print “List is:” ,x
for a in x:
s=a*a*a
print s
sum=sum+a
print sum
av=(float)sum/n
print “Average:”,av
x =[]
sum=0
n=input(“enter the no.of elements”)
print "\nEnter the Elements"
for i in range(1,n+1):
k=input()
Here ‘a’ stores the elements of the list one by
x.append(k)
one.. cube of each value is calculated ad stored
print “List is:” ,x
in s. sum of cubes are stored in the variable sum.
for a in x:
s=a*a*a
print s
sum=sum+s
print sum
Refer note
• matrix3 is a list in which individual elements are lists that represent rows of that matrix.
• Here list ‘a’ is used to store each row of matrix3.
• each row contains n elements.
• within inner loop the elements of a row are calculated as the sum of elements in the same row
of matrix1 and matrix2 and the resultant elements are append to list ‘a’.
Eg. row 2 of matrix 3= sum of corresponding elements of row2 of matrix1 and matrix2
• Then that row (ie list a) is appended to matrix3
for k in matrix2:
print k
x =[]
n=input(“How many names?”)
print "\nEnter the names"
for i in range(1,n+1):
The names in the list are sorted
k=raw_input()
x.append(k)
print “List is:” ,x
Here ‘a’ stores the names in the list one
x.sort() by one..
print “Sorted List:”,x
Then the names are stored in b after
for a in x:
converting in to uppercase .
b=a.upper()
Then these names are displayed
print b
i) data[2] = 89
ii) print data[4][2]
iii) data.remove(56)
Output :
list : [‘Apple’ , ‘orange’ , ‘grapes’ ]
➢ Keys are unique within a Dictionary while values may not be unique.
➢ The values can be of any type but the keys must be of an immutable datatype such as
numbers, strings or tuples.
➢ Dictionary is mutable .We can add new items or change the values of existing items
DICTIONARY OPERATIONS
1. Dictionary Creation
2. Displaying dictionary
3. Dictionary Traversal
4. Updating dictionary elements
5. Deletion of Dictionary elements
6. Membership operations DHANYA V,AP IN IT,CEV 1
Downloaded from Ktunotes.in
DICTIONARY OPERATIONS
CREATING A DICTIONARY
➢ A Dictionary is created by enclosing the all the items inside curly brackets ({}) separated
by commas
Syntax : Dictionary name={ key1 : value1 , key2 : value2 , key3 : value3 ,……….}
DICTIONARY LENGTH
➢ The function len is used to find the length of a Dictionary(number of items in the
dictionary)
Syntax: len(Dictionary name)
for i in student: Here ‘i’ represents each key in the Output: RollNo : 10
print i, “:” ,student[i] dictionary. Name : John
So here keys and values are
displayed one by one mark : 280
dictionary[key] =value
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
student [“mark”] = 290
Now,student = { “RollNo” : 10 , “Name” : “John” , “mark” : 290}
print “Present”
else:
Output :Present
print “Not Present”
len()
❑ This method is used to find the length of the dictionary(ie no.of items in the dictionary)
keys()
❑ This method is used to return a list of keys from the Dictionary .
Syntax: dictionary name. keys()
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
a= student. keys()
a= [“RollNo” , “Name” , “mark” ]
items()
❑ This method is used to return a list of (key,value) pairs from the Dictionary .
Syntax: dictionary name. items()
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
a= student. items()
a= [ (“RollNo” ,10) , (“Name”, “John”) , (“mark” ,280) ]
popitem()
❑ This method is used to remove and return an arbitrary item in a Dictionary .[Python2]
Syntax: dictionary name. popitem() Note : We can use del
statement also to delete
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 } an element from
t= student. popitem() dictionary
Note: In Python3, It removes the last item in the dictionary
sorted()
❑ This method is used to return a sorted list of keys from the Dictionary
Syntax: sorted(dictionary name) [Ascending order sorting]
a = sorted(dictionary name,reverse=True) [descending order sorting]
Eg: student = { 10:”John” , 1: “Ann” , 8: “James” }
a= sorted(student) b=sorted(student , reverse=True)
a= [ 1,8,10] b=[10,8,1]
Syntax :
1. dictionary name .update(key = value) – Update with key-value pair
Eg1: data ={“a”:10, “b”:20}
data.update(“c”=30) → data ={“a”:10, “b”:20,”c”:30}
Eg2: data ={“a”:10, “b”:20}
data.update(“b”=30) → data ={“a”:10, “b”:30}
2. dictionary name.update(dictionary2) –Update with dictionary2
Eg1: data ={“a”:10, “b”:20} data2={ 5 : 50 , 1:100}
data.update(data2) → data ={“a”:10, “b”:20,” 5:50 ,1:100}
DHANYA V,AP IN IT,CEV 15
Downloaded from Ktunotes.in
DICTIONARY COPYING
1.Using Assignment operator(=) Here d1 and d2 represent same memory locations
d1={1:1,2:4 ,3:9} where the dictionary values are stored. So when
d2=d1 one variable is updated the change will be reflected
d1[4] = 16 in other variable also.
print “d1=“, d1 , “\nd2 =“ ,d2 Output
d1={1:1,2:4 ,3:9 ,4:16}
d2={1:1,2:4 ,3:9 ,4:16}
2.Using copy() function Here a copy of dictionary values are stored in d2(in
d1={1:1, 2:4 , 3:9} different memory locations) So when one variable is
d2=d1.copy() updated it will not affect the other variable.
d1[4] = 16 Output
print “d1=“, d1 , “\nd2 =“ ,d2 d1={1:1,2:4 ,3:9 ,4:16}
d2={1:1, 2:4 , 3:9 }
Suppose name is used as key(Assume that names are unique) . So we need to sort in asc
order of keys for loop executes 5 times. so we can enter detais of 5
student={} students .
for i in range(1,6):
student[s]= r means the key value pair(s,r) is inserted
r= input("enter roll no:") in the dictionary student. ie name is used as key and
s=raw_input("enter name:") roll no as value corresponding to that key
student[s]=r
print student The keys of dictionary(student) are sorted and
t=sorted(student) stored in the list ‘t’
for i in t:
Traverse list ‘t’ . here ‘i’represents each element in
print i, student[i] the list (ie keys in the dictioary in sorted order)
A Dictionary is created by enclosing the all the items inside curly brackets ({})
separated by commas
Syntax : Dictionary name={ key1 : value1 , key2 : value2 , key3 : value3 ,……….}
Eg: weekdays= {1: “Sunday” , 2: “Monday “ , 3: “Tuesday “, 4: “Wednesday”}
To read a sparse matrix using dictionary we read the non zero element and it’s row
and column indices
m=input("Enter no.of rows of sparse mat: ")
n=input("Enter no.of columns: ")
matrix1=[]
print "\nEntering the Elements for sparse matrix1....."
for i in range(0,m):
The non-zero elements are added to the
a=[] dictionary .
Key : tuple representing row index and column
for j in range(0,n): index of nonzero value.
value : The nonzero value
k=input()
a.append(k) For eg: if row and col index of nonzero value 7
are 1 and 3 resp: then the dictionary entry
matrix1.append(a) corresponding to that non zer value is (1,3) : 7
D={}
for i in range(0,m):
for j in range(0,n):
if(matrix1[i][j] !=0):
D[(i,j)] = matrix1[i][j]
Print “Sparse Matrix in Dictionary representation:” ,D
➢ The values can be of any type but the keys must be of an immutable datatype
such as numbers, strings or tuples.
Eg: student = { “RollNo” : 10 , “Name” : “John” , “mark” : 280 }
dictionar operations (Briefly explain any 5)
1. Dictionary Creation 2. Displaying dictionary
3. Dictionary Traversal 4. Updating dictionary elements
5.Deletion of Dictionary elements 6.Membership operations
Refer Note.
keys(),values().items(),clear(),pop() etc
Suppose name is used as key (Assume that names are unique) . So we need to sort in asc
order of keys
D={}
for i in range(1,6):
s=raw_input("enter name:")
p= input("enter phone no:")
D[s]=p
print D
t=sorted(D)
for k in t:
print k, D [k]
Refer Note.
Syntax: dictionary.has_key(key)
i) farm[“Ducks”] = 8
ii) print len(farm)
iii) del farm[“Cows”] or farm.pop(“Cows”)
stock ={}
stock[‘pencil’]=400
stock[‘pen’]=1000
stock[‘eraser’]=200
stock[‘ink’]=50
i) print stock
ii) del stock[‘ink’]
print stock
iii) A Dictionary is an unordered collection of items.Each item has a key and a
corresponding value that is expressed as a pair (key: value).
The (key,value) pairs can be written in any order.
Keys are unique within a Dictionary while values may not be unique.
The values can be of any type but the keys must be of an immutable datatype
such as numbers, strings or tuples.
• To find no. of key-value pairs(no.of elements in the dictionary) , we can use len(stock)
• Keys : pencil,pen,eraser,ink
• To display a list of keys , use the statement print stock.keys()
print "Menu\n 1.Add books\n 2.Sell books\n 3.Exit" Display choice menu
Data={}
n=input(“Enter no.of account holders:”)
for i in range(1,n+1):
a=input("enter account no:")
b= input("enter account balance:")
Data[a]=b
while (True):
print "Menu\n 1.Deposit\n 2.Withdraw\n 3.Exit"
c=input("Enter your choice:")
if c==1:
ac=input("Enter account no:")
amt=input("Enter amount to deposit:")
Data[ac] =Data[ac]+amt
print Data
elif c==2:
ac=input("Enter account no:")
amt=input("Enter amount to withdraw:")
if amt>books[ac]:
print “Insufficient Balance!!”
else:
Data[ac] =Data[ac]-amt
print Data
elif c==3:
break
else:
print "\n\tEnter valid choice(1/2/3)!!!!"
items = {"Laptop":100,"MobilePhone":200,"Camera":150}
while (True):
print "Menu\n 1.Add Items\n 2.Delete Items\n 3.Exit"
a=input("Enter your choice:")
if a==1:
i=raw_input("Enter item:")
n=input("Enter no.of units:")
items[i]=items[i]+n
print items
elif a==2:
i=raw_input("Enter item:")
n=input("Enter no.of units:")
if n>items[i]:
items[i]=0
else:
items[i]= items[i]-n
print items
elif a==3:
break
else:
print "\n\tEnter valid choice(1/2/3)!!!!"