Ch 10 Tuples & Dictionary
Ch 10 Tuples & Dictionary
Creating tuples
Syntax:
Tuple-name=() # empty tuple
Tuple-name=(element 1,element 2,….element n)
Eg: >>>T = ()
>>>T = (23,78,’a’,’hello’)
>>>T
(23,78,’a’,’hello’)
Accessing Tuples
Tuples are similar to lists. Tuple elements are also indexed.
Forward Indexing – 0,1,2-------n-1
Backward Indexing- -1,-2,-3--------- - n
The values stored in a tuple can be accessed using the slice operator ([ ],[ : ]) with
indices.
Tuple_name[start:end] will give you elements between the indices start to end-1
Eg: >>> T1=(‘p’,’y’,’t’,’h’,’o’,’n’)
0 1 2 3 4 5
p y t h o n
-6 -5 -4 -3 -2 -1
>>> T1[4]
‘o’
>>>T1[-5]
‘y’
>>>T1[10]
Index Error, tuple out of range
Traversing a Tuple
1. Using for loop
Syntax: for<variable>in tuple_name:
Statement
Eg: >>>a=(1,2,3,4,5)
>>>for i in a:
print(i)
OUTPUT:
1
2
3
4
5
2. Using for loop with range function
Syntax: for<variable>in range(0,len(tuple_name)):
Statement
Eg. >>>a1=(‘a’,’b’,’c’,’d’)
>>>for i in range(0,len(a1)):
Print(a1[i],end=””)
OUTPUT:
abcd
3. Using while loop
Syntax:
i=0
while i<len(tuple_name)):
print(tuple_name[i])
i=i+1
eg.a1=(‘a’,’b’,’c’,’d’)
i=0
while i<len(a1):
print(a[i]
i=i+1
OUTPUT:
1
2
3
4
5
TUPLE OPERATIONS
❖ Concatenation Operator
❖ Repetition Operator
❖ Slice Operator
❖ Comparison or Relational Operator
❖ Membership Operator
Eg. >>>T1=(1,3,7)
>>>T2=(2,4,6)
>>>T2+T1
(2,4,6,1,3,7)
>>>T1+3
Type Error: Can only concatenate tuples , not integer and tuple.
>>>T1 + 8,
(1,3,7,8)
2. Repetition Operator (*) : It replicates a tuple specified no. of times.
Eg. >>> T1=(1,2,3)
>>>T1*2
(1,2,3,1,2,3)
>>>T2=(10,20,30,40)
>>>T2[2:4]*3
(30,40,30,40,30,40)
3. Slice Operator ([:])
tuple_name[Start : End] will give you elements from Start to End -1
eg: >>>T1=(1,2,3,4,5,6,7)
>>>T1[2:4]
(3,4)
>>>T1[3:20]
(4,5,6,7)
>>>T1[3:]
(4,5,6,7)
>>>T1[-1:-5]
() # returns empty tuple, start should be always less than end.
>>>T1[-5:-1]
(3,4,5,6)
1. len() – Returns the length or number of the elements of the tuple passed as the
argument.
Eg. >>>T1=(10,20,30,40,50
>>>len(T1)
5
2. tuple() – Creates an empty tuple if no argument is passed.
>>> T1=tuple()
>>>T1
()
Creates a tuple if a sequence is passed as argument.
>>>T1=tuple(‘aeiou’) # string
>>>T1
(‘a’,’e’,’I’,’o’,’u’)
>>>T2=tuple([1,2,3]) # list
(1,2,3)
>>>T3=tuple(range(5))
>>>T3
(0,1,2,3,4)
3. count() – Returns the no. of times the given element appears in the tuple.
Syntax: tuple_name.count(element to be counted)
Eg. >>>T1=(10,20,30,10,80,10,70,10)
>>>T1.count(10)
4
>>>T1.count(90)
0
4. index() – Returns the index of the first occurrence of the element in the given tuple.
Syntax: tuple_name.index(element)
Eg. >>>T1=(10,20,30,20,40)
>>>T1.index(20)
>>>T1.index(50)
5. sorted()- Takes elements in the tuple and returns a new sorted list. It should be
noted that, sorted() does not make any change to the original tuple.
Syntax: sorted(tuple_name)
Eg. >>>T1=(“Red”,”Green”,”Blue”,”White”)
>>>sorted(T1)
(“Blue”,”Green”,”Red”,”White”)
6. min() – Returns minimum or smallest element of the tuple.
7. max() – Returns maximum or largest element of the tuple.
8. sum() – Returns sum of the elements of the tuple.
Eg. >>>T1=(1,2,3,4,5)
>>>min(T1)
1
>>>max(T1)
5
>>>sum(T1)
15
Nested Tuple
A tuple inside another tuple is called a nested tuple.
Eg.
st=((101,"Aman",98),(102,"Geet",95),(103,"Sam",87))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])
Output:
S_No Roll_No Name Marks
1 101 Aman 98
2 102 Geet 95
3 103 Sam 87
Tuple Assignment
Eg. >>>num1,num2=(10,20)
>>>num1
10
>>>num2
20
Deleting a Tuple
The del statement is used to delete elements and objects, but as you know that
tuples are immutable which also means that individual elements of a tuple cannot
be deleted.
Eg. >>>T1=(1,2,3,4,5)
>>>del T1[3]
Type Error: Tuple object does not support item deletion.
>>>del T1
>>>T1
Type Error: name T1 not defined
Programs in Tuples
OUTPUT:
else:
OUTPUT:
45 found at index=2
DICTIONARY
Syntax:
Dict_name={key1:value1,key2:value2…………keyn:valuen}
Eg. >>>dict1={1:100,2:200,3:300}
>>>dict1[3]=500
>>>dict1
{1:100,2:200,3:500}
Dictionary_name[‘key’/key]=new-value
Note : The same format can be used to add new item in dictionary. The dictionary is
indexed by keys, keys are immutable.
Mapping
Internally key-value pairs are associated with one another with some internal
functions called as hash. This way of linking is called mapping.
Key Hash Function Stored values
Key 1 Value 3
Key2 Value 1
Key3 Value 4
Key4 Value 2
Creating a Dictionary
Empty Dictionary – It can be created using curly brackets
>>>D1={}
>>>D1
{}
It can also be created using dict() function
>>>D1=dict()
>>>D1
{}
Creating Dictionary with many elements
Eg. Following Dictionary maps names of the students to respective marks in
percentage:
>>>D1={‘Mohan’:95,’Ram’:89,’Sam’:98}
>>>D1
{‘Mohan’:95,’Ram’:89,’Sam’:98}
Traversing a Dictionary
We can access each item of the dictionary or traverse using for loop.
Eg. >>>D1={‘a’:10,’b’:20.’c’:30}
Method – 1
>>>for key in D1:
Print(key,’:’,Dd1[key])
Output:
a:10
b:20
c:30
Method-2
>>>for key,value in D1.items():
Pint(key,’:’,value)
Output:
a:10
b:20
c:30
Dictionary Operation
Membership Operator(in, not in)
in Operator- It checks if key is present in the given dictionary, then return True
otherwise False.
not in Operator- It returns True if key is not present in the given dictionary, otherwise
False.
Eg. >>>D1={‘a’:10,’b’:20.’c’:30}
>>>’a’ in D1
True
>>>’d’ not in D1
True
>>>’a’ not in D1
False
>>>x=(sorted(D1.keys()))
>>>print(x)
[1,2,3,5]
>>>x=(sorted(D1.values()))
>>>print(x)
[101,102,103,104]
for k in Emp:
print(k,’\t\t\t’,Emp[k])
OUTPUT:
Enter the number of employees: 3
Enter employee name: John
Enter employee salary: 80900
Enter employee name: Sam
Enter employee salary: 75000
Enter employee name: Mohan
Enter employee salary: 80000
OUTPUT:
Enter the string=HelloWorld
H:1
e:1
l:3
o:2
W:1
r:1
d:1
**************************