0% found this document useful (0 votes)
5 views

Ch 10 Tuples & Dictionary

The document provides an overview of tuples and dictionaries in Python, detailing their properties, creation methods, and operations. It explains tuple characteristics such as immutability, indexing, and methods for accessing and manipulating tuples, as well as dictionary features including key-value pairs, creation, and accessing elements. Additionally, it covers tuple operations like concatenation, repetition, and slicing, along with built-in functions for both data structures.

Uploaded by

ai.crimson158
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)
5 views

Ch 10 Tuples & Dictionary

The document provides an overview of tuples and dictionaries in Python, detailing their properties, creation methods, and operations. It explains tuple characteristics such as immutability, indexing, and methods for accessing and manipulating tuples, as well as dictionary features including key-value pairs, creation, and accessing elements. Additionally, it covers tuple operations like concatenation, repetition, and slicing, along with built-in functions for both data structures.

Uploaded by

ai.crimson158
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/ 25

Chapter-1

TUPLES AND DICTIONARY


TUPLES
➢ Tuple is a collection of elements which is ordered and unchangeable(immutable).
➢ Allows duplicate elements.
➢ Consists of values or elements of any data type separated by comas.
➢ Tuples are enclosed within parenthesis.
➢ Cannot remove the elements from a tuple.

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’)

Creating a tuple with single elements:


Eg: >>>T = (3) # It is an integer not a tuple
>>>T
3 # It is an integer
Eg: >>>T = (3,) # to construct a tuple, use a comma after the single element
>>>T
(3,)

Creating a tuple using tuple () construction


Eg: >>>T = tuple () # empty tuple
>>>T1 = tuple ( ( 4,39,’K’,22) ) # taking all elements as a single
>>>T 1
(4,39,’K’,22)

Eg: >>>T2= tuple (‘hello’) Taking as diff elements, So it will be separated.


>>>T2
(‘h’,’e’,’l’,’l’,o) #for single parenthesis, the argument must be of sequence data
type
Eg:>>>T3=(‘hello’,’python’) It is operated with comma. So it is already a tuple.
>>>T3
(‘hello’,’python’)

Creating a tuple taking input from user

eg: >>>T1=tuple (input (“Enter the elements:”))


Enter the element :hello
>>>T1
(‘h’,’e’,’l’,’l’,’o’)
>>>T1= tuple (input(“Enter the element:”))
Enter the elements:45689
>>>T1
(‘4’,’5’,’6’,’8’,’9’) #It treats elements as character through entered as digits.
To overcome the above problem we use eve() method, which identifies the datatypes
and evaluate it automatically.
EG: >>>T1 = eval (input(“Enter the elements:”))
Enter the elements: (2,’a’,’hello’,7.8) #parenthesis is optional
>>>T1
(2,’a’,’hello’,7.8)
Eg. >>>T2 = eval (input(“Enter the elements:”))
Enter the elements:54386
>>>T2
54386 #It is an integer
>>>type(T2)
<class ’int’>
>>>type(T1)
<class ‘tuple’>
Eg. >>>T3=eval(input(“Enter the elements:”))
Enter the elements: 2,4,6,[3,8,6] ( list inside a tuple)
>>>type(T3)
<class ‘tuple’>
Eg. >>>T4=eval(input(“Enter the elements=”))
Enter the elements=34,
>>>T4
(34,)
>>> type(T4)
<class ‘tuple’>

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

1. Concatenation or Joining Operator (+) : It joins two or more tuples.

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)

tuple_name[start:end:step] will give you elements between indices start to end -1


with skipping elements as per the value of step.
Eg. >>>T1=(1,2,3,4,5,6,7)
>>>T1[1:5:2]
(2,4)
>>>T1[::-1] # reversing tuple
(7,6,5,4,3,2,1)
>>>T1[::-2]
(7,5,3,1)
>>>T1[::2]
(1,3,5,7)
4. Comparison or relational operator (<,<=,>,>=,==,!=)
It compares two tuples. Python internally compares individual elements of tuples in
lexicographical order.
For equal comparisons, it compares each corresponding elements and two sequences
must be of same type.
For non- equal comparisons, as soon as it gets the result in terms of True or False, from
corresponding elements comparison. If corresponding elements are equal, it goes to
next element and so on, until it finds elements that differ.
Eg. >>>T1=(9,8,10)
>>>T2=(9,8,10)
>>>T3=(‘9’,’8’,’10’)
>>>T1==T2
True
>>>T1==T3
False
>>>T4=(9.0,8.0,10.0)
>>>T1==T4
True
>>>T1<T2
False
>>>T1<=T2
True
5. Membership Operator (in, not in)
Eg. >>>T1=(‘Red’,’Green’,’Blue’)
>>>’Green’ not in T1
True
>>>’Green’ not in T1
False

Tuple Methods and Built in Functions

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)

Value Error: Value not in tuple

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

Tuple Packing & Unpacking


Tuple Packing: Creates a tuple from set of values
>>>T1=(4,7,8)
>>>T1
(4,7,8)
Tuple Unpacking : Creating individual values from the elements of tuples.
Eg. >>>T1=(4,7,8)
>>>a,b,c =T1
>>>a
4
>>>b
7
>>>c
8
Note : Tuple unpacking requires that the no. of variables on the left side must be
equal to the length of the tuple.
>>>(a,b,c,d)=(5,6,8)
Value Error :not enough values to unpack

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

1. Program to find the smallest and largest number in the tuple.

T=eval(input(“Enter the elements in the tuple=”))


Smallest= Largest =T[0]
Sindex= Lindex =0
for i in range(len(T)):
if T[i] > Largest:
Largest = T[i]
Lindex = i
elif T[i] < Smallest:
Smallest=T[i]
Sindex=i
Print(“The smallest number=”,Smallest,”at index=”,Sindex)
print("The largest number =", Largest, "at index =", Lindex)

OUTPUT:

Enter the elements in the tuple=(7,19,23,29,15,3,20)


The smallest number=3 at index =5
The largest number=29 at index=3
2. Program to input a tuple of elements and search for a given
element(Linear Search)

T=eval(input(“Enter the elements in the tuple=”))


val=int(input(“Enter the element to be searched=”))
for I in range(len(T)):
if val==T[i]:
print(val,”found at index=”,i)
break

else:

print(val,”not found in the given tuple”)

OUTPUT:

Enter the elements in the tuple=(23,78,45,89,97,12)


Enter the value to be searched=45

45 found at index=2
DICTIONARY

Dictionary is an unordered collection of items (key-value pair)


➢ It is a mapping between set of keys and set of values. The key – value pair is called
‘item’.
➢ Elements of dictionaries are enclosed in curly brackets{ } and are separated by
commas.
➢ Dictionaries are datatypes in the form of key:value, where mutable key is used for
accessing corresponding values.
➢ Keys are unique within a dictionary and are immutable datatypes, where values are
mutable datatypes(any datatype)

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}

Accessing keys ad values


To access keys of a dictionary , use keys() function.
Eg. >>>D1={‘Mohan’:95,’Ram’:89,’Sam:98}
>>>D1.keys()
dict_keys([‘Mohan’,’Ram’,’Sam’])
To access values of a dictionary, use values() function.
Eg. >>>D1.values()
dict_values([95,98,78])

Accessing elements in a Dictionary


The items of a dictionary are accessed with the keys rather than their relative
positions or indices / index value. Each key serves as index and maps to a value.
Eg. >>>D1={‘Mohan’:95,’Ram’:89,’Sam:98}
>>>D1[‘Ram’]
98
>>>D1[‘Aman’]
Key Error: ‘Aman’ does not exist

Adding elements in a dictionary


Eg. >>>D1={‘Mohan’:95,’Ram’:89,’Sam:98}
>>>D1[‘Aman’]=78
>>>D1
{‘Mohan’:95,’Ram’:89,’Sam:98,’Aman’:78}
New key-value pair (item) is added at the end of the dictionary as last item.

Updating or Modifying items in a dictionary


The existing dictionary can be modified as altered by replacing or overwriting the
corresponding keys. If the key is not present it will add the key-value pair at the end
of the dictionary.
Eg. >>>D1={‘Mohan’:95,’Ram’:89,’Sam:98}
>>>D1[‘Ram’]=78
>>>D1
{‘Mohan’:95,’Ram’:78,’Sam:98}
>>>D1[‘Aman’]=56
>>>D1
{‘Mohan’:95,’Ram’:78,’Sam:98,’Aman’:56}

Deleting elements in a Dictionary


Using del method
Syntax: del dictionary_name[key/’key’]
It will delete the item from dictionary whose key is passed as an argument,
no value will be returned.
Eg. >>>D1={‘a’:10,’b’:20.’c’:30}
>>>del D1[2]
D1
{‘a’:10.’c’:30}
Using pop()
It will remove and return the element associated to the passed key.
Using popitem()
It will remove the last item in the dictionary and return key-value pair.

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

Built in Functions in Dictionary


fromkeys() Returns new Dictionary with >>>k=(‘a’,’e’,’I’,’o’,’u’)
the given set of elements as >>>D=dict.fromkeys(k,’vowel’)
the key of the Dictionary. >>>print(D)
{‘a’:vowel,’e’:vowel,’I’:vowel,’o’:vowel,’u’ :vowel}
dict.fromkeys(key,value)
>>>E=(‘name’,’salary’,’age’)
>>>Emp=dict.fromkeys(E)
>>>print(Emp)
{‘name’:None,’salary’: None,’age’: None}

setdefault() Returns the value of the item >>>car={‘brand’:”Ford”,”model”:”Mustang”,”year”:2000}


with the specified key. If the >>>x=car.setdefault(“color”,”white”)
key does not exist, insert the >>>print(x)
key with the specified value. White
>>>print(car)
{‘brand’:”Ford”,”model”:”Mustang”,”year”:2000,”color”:”White”}

sorted() This function is used to sort >>>D1={1:101,3:102,5:103,2:104}


the key or value of Dictionary >>>print(sorted(D1))
in either ascending or [1,2,3,5]
descending order. By default it
will sort the keys. To display in Descending order
>>>print(sorted(D1,reverse=’True’))
[5,3,2,1]

>>>x=(sorted(D1.keys()))
>>>print(x)
[1,2,3,5]

>>>x=(sorted(D1.values()))
>>>print(x)
[101,102,103,104]

min() Returns the lowest value in >>>D1={2:101,5:102,1:103,4:104}


Dictionary. >>>print(min(D1.values()))
101
>>>print(min(D1.items()))
(1,103)
max() Returns the highest value in >>>D1={2:101,5:102,1:103,4:104}
Dictionary. >>>print(max(D1.keys()))
5
>>>print(max(D1.items()))
(5,102)

copy() It creates a copy of Dictionary >>>D1={1:101,2:102.3:103}


>>>D2=D1.copy()
>>>D2
{1:101,2:102.3:103}

pop() It will remove and returns the >>>D1={‘a’:10,’b’:20,’c’:30}


dictionary element associated >>>x=D1.pop(‘b’)
to the passed key. >>>print(x)
20
>>>D1
{‘a’:10,’c’:30}

popitem() It will remove the last >>>D1={‘a’:10,’b’:20,’c’:30}


dictionary item and return >>>k,v=D1.popitem()
key-value of the removed >>>print(k,”:”,v)
item. C:30
Important Programs
1. Program to create a dictionary with roll no,name of the student in a
class and display the name of students who have scored marks above
75.
N=int(input(“Enter the total no. of students=”))
D={}
for i in range(N):
roll no=int(input(“Enter roll no=”))
name=input(“Enter name=”)
marks=float(input(“Enter marks=”))
D[roll no]=[name,marks]
print(“Students scored marks above 75=”)
for i in D:
if D[i][1]>75:
print(D[i][0])
OUTPUT:
Enter the total no. of students=2
Enter roll no=101
Enter name=Raj
Enter marks=80
Enter roll no=102
Enter name=Sam
Enter marks=60
Students scored marks above 75=
Raj
2. Program to enter names of employees and salaries as input and store
them in a dictionary and print it.
N= int(input("Enter the number of employees: "))
Emp=dict()
for i in range(N):
name = input("Enter employee name: ")
salary = float(input("Enter employee salary: "))
Emp[name] = salary
print("\n Employee Name \t\t Salary")

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

Employee Name Salary


John 80900.0
Sam 75000.0
Mohan 80000.0
3. Program to count the no. of times a character appears in a given string
using a dictionary.

Str=input("Enter the string=")


D={}
for ch in Str:
if ch in D:
D[ch]+=1
else:
D[ch]=1
for k in D:
print(k,":",D[k])

OUTPUT:
Enter the string=HelloWorld
H:1
e:1
l:3
o:2
W:1
r:1
d:1

**************************

You might also like