U18CSI2201 - Unit 4 Tuples and Dictionaries 1
U18CSI2201 - Unit 4 Tuples and Dictionaries 1
UNIT – IV
Suppose it is mandatory to have the following types of food in the lunch menu of
the airline passengers.
Welcome Drink, Veg Starter, Non-Veg Starter, Veg Main Course, Non-Veg Main
Course, Dessert
How can we store it such that no one can modify the elements?
Of course, we can use a list but anybody can modify an element in the list. This is
where we can use another collection data type known as tuple.
Tuples
• Same as lists but
• Immutable
• Enclosed in parentheses ( )
• Elements of tuples are fixed and are read-only
• A tuple with a single element must have a comma inside the
parentheses:
• a = (11,)
Example for tuple:
rainbow=("violet","indigo","blue","green","yellow","orange","red")
Creating Tuples
• Creating a tuple using the constructor of tuple class as:
T1=tuple() or T1=() #Creates an Empty tuple object
T2=tuple(1,2,3,4) #Creates a tuple object
T3=1,2,3,4 # Creates a tuple without parenthesis
p y t h o n
Example:
>>> lang = (‘p’,’y’,’t’,’h’,’o’,’n’) 0 1 2 3 4 5
>>> lang[0] #Access the first element of the tuple.
‘p'
>>>lang[-1] #Access the last element of the tuple. (Negative index)
‘n’
Tuple slices
• The slicing operator returns a subset of a string called slice by
specifying two indices, start and end
Syntax:
String name[start_index:end_index]
Example:
>>>T=(1,4,5,2,6,3,4)
>>>S[2:5] #returns subset of a tuple
(5,2,6)
Tuple +,* and in operators
+ operator : Concatenation operator ‘+’ is used to join two tuples.
Example:
>>>t1=(1,3,5)
>>>t2=(2,4,6)
>>>t1+t2
(1,3,5,2,4,6)
* operator: Multiplication (*)operator is used to concatenate the same tuple
multiple times. Also called as repetition operator.
Example:
>>>t1=(1,2)
>>>t2=3*t1 # 3*t1 and t1*3 gives the same output
>>>t2
(1,2,1,2,1,2)
Examples
>>> mytuple = (11, 22, 33)
>>> mytuple[0]
11
>>> mytuple[-1]
33
>>> mytuple[0:1]
(11,)
The comma is required!
Single value within () not a tuple
• No confusion between (11) and 11
Output:
('HP', 'DELL', 'APPLE')
(34000, 26000, 75000)
Program to transpose a matrix using zip(*)
>>>matrix=[(1,2,3),(4,5,6),(7,8,9)]
>>>matrix
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
>>>x=zip(*matrix)
>>>tuple(x)
((1, 4, 7), (2, 5, 8), (3, 6, 9))
List methods of lists and tuples
>>> dir(list)
>>>dir(tuple)
Help command in python
>>> help(list.append)
Help on method_descriptor:
append(self, object, /)
Append object to the end of the list.
>>> help(tuple.count)
Help on method_descriptor:
count(self, value, /)
Return number of occurrences of value.
Program to traverse tuples from a list
T=[(10,"Sachin"),(7,"Dhoni"),(18,"Virat")]
print("Jersey Name")
for jersey,name in T:
print(jersey," ",name)
Output:
Jersey Name
10 Sachin
7 Dhoni
18 Virat
Tuples as Return Values
• To divide two integers and compute the quotient and remainder, it is
inefficient to compute x/y and then x%y. It is better to compute them
both at the same time.
• The built-in function divmod takes two arguments and returns a tuple
of two values: the quotient and remainder.
• You can store the result as a tuple:
>>> quot, rem = divmod(7, 3)
>>> t = divmod(7, 3) >>> quot
>>> t 2
>>> rem
(2, 1)
1
Variable-Length Argument Tuples
• Functions can take a variable number of arguments. A parameter name
that beginswith * gathers arguments into a tuple.
def printall(*args):
print(args)
>>> printall(1, 2.0, '3')
(1, 2.0, '3')
• The complement of gather is scatter. If you have a sequence of values and
you want to pass it to a function as multiple arguments, you can use the *
operator
>>> t = (7, 3)
>>> divmod(*t)
(2, 1)
QUIZ
Which among the following statements may result in an error?
Assume that the statements are executed in the order in which it is written.
a. tuple1=(5,10,15,20,25)
b. print(len(tuple1))
c. tuple1[2]=100
d. print(tuple1[5])
e. tuple1=tuple1+(8,9,"h")
Options:
Ans: c and d
e
d
d and e
c and d
>>>tuple1=(5,10,15,20,25)
>>> print(id(tuple1))
Output:
>>> tuple1=tuple1+(8,9,"h")
>>> print(tuple1) 2357607874720
(5, 10, 15, 20, 25, 8, 9, 'h')
>>> print(id(tuple1)) 2357607903304
DICTIONARIES
Dictionaries
• Dictionary is a collection that stores values along with keys
• Store pairs of entries called items
{ ‘Rollno’ : ‘19BEE001', ‘Name' : ‘Adarsh'}
• Each pair of entries contains
• A key
• A value
• Key and values are separated by a colon
• Pairs of entries are separated by commas
• Dictionary is enclosed within curly braces { and }
Usage
• Keys must be unique within a dictionary
• No duplicates
• If we have
age = {'Alice' : 25, 'Bob' :28}
then
age['Alice'] is 25
and
age[Bob'] is 28
Dictionaries are mutable
>>> age = {'Alice' : 25, 'Bob' : 28}
>>> saved = age
>>> age['Bob'] = 29
>>> age
{'Alice': 25, 'Bob': 29}
>>> saved
{'Alice': 25, 'Bob': 29}
Keys must be unique
>>> age = {'Alice' : 25, 'Bob' : 28, 'Alice' : 26}
>>> age
{'Bob': 28, 'Alice': 26}
Displaying contents
>>> age = {'Alice' : 25, 'Carol': 'twenty-two'}
>>> age.popitem()
('Bob', 29)
>>> age
{'Carol': 23, 'Alice': 26}
>>> age.popitem()
('Carol', 23)
>>> age
{'Alice': 26}
Traversing dictionaries
likes = {'Ram': 'Python', 'Mano': 'English', 'Ranjitha': 'Chemistry'}
Output:
Ram likes Python
Mano likes English
Ranjitha likes Chemistry
----------------------------------------------------------------------------------------------
likes = {'Ram': 'Python', 'Mano': 'English', 'Ranjitha': 'Chemistry'}
for key in likes.keys():
print(key,"likes",likes[key])
Output: Same as above
Traversing dictionaries (Continues)
likes = {'Ram': 'Python', 'Mano': 'English', 'Ranjitha': 'Chemistry'}
Output:
Python
English
Chemistry
----------------------------------------------------------------------------------------------
likes = {'Ram': 'Python', 'Mano': 'English', 'Ranjitha': 'Chemistry'}
for key in likes:
print(likes[key])
Output: Same as above
Simple programs on Dictionary
# occurrence of the character in the slogan
Slogan="character is life"
occur=dict()
for char in Slogan:
if char not in occur:
occur[char]=1
else:
occur[char]=occur[char]+1
print(occur)
Output:
{'c': 2, 'h': 1, 'a': 2, 'r': 2, 't': 1, 'e': 2, ' ': 2, 'i': 2, 's': 1, 'l': 1, 'f': 1}
Simple programs on Dictionary (Contd…)
# Create dictionary with square value for a given list
list=[5,6,1,3,8,1,6]
square=dict()
for num in list:
square[num]=num*num
print(square)
Output:
{5: 25, 6: 36, 1: 1, 3: 9, 8: 64}
Program to convert an octal number to
binary
def oct_bin(number,table): Output:
binary=''
for digit in number: Enter octal number for conversion:553
Given octal number in binary is: 101101011
binary=binary+table[digit]
return binary
oct_bin_table={'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110','7':'111'}
Example :
>>> movies['TITANIC']['Hero']
'Leonardo DiCaprio'
>>> movies['GODZILLA']['Director']
'Gareth Edwards'
Traversing Nested Dictionaries
IPL={"CSK":{"Owner":"Srinivasan","Captain":"Dhoni"}, Output :
"RCB":{"Owner":"Mallaiah","Captain":"Kohli"}, CSK
Owner is Srinivasan
"MI":{"Owner":"M Ambani","Captain":"Rohit"},
Captain is Dhoni
"KKR":{"Owner":"Sharukh","Captain":"D Karthik"}}
RCB
Owner is Mallaiah
for team_name,team_details in IPL.items(): Captain is Kohli
print(team_name) MI
for key in team_details: Owner is M Ambani
print(" ",key,"is",team_details[key]) Captain is Rohit
KKR
Owner is Sharukh
Captain is D Karthik
Programs
1. Write a program to pass a list to a function. Calculate the total number of
positive , zeros and negative numbers from the list and then display the
count in terms of dictionary.
lst = [7,-2,8,0,6,-34,0,76,-90]
di = print_count(lst)
print(di)
Solution for Ex.2 currency convertor
currency={"US dollar":0.014,"Brazilian Real":0.055,"Singapore
dollar":0.02,"Malasian Ringgit":0.059}
rupee=eval(input("Enter the rupees you have:"))
curr=input("Enter the name of currency:")
Enter the rupees you have: 1000
a. Error
b. 0 b.0
c. NULL
d. Empty
Quiz
2.What will be the output of the following:
t=(5,1,2,7,8)
t[2]=10
print(t)
a. (5,1,2,10,7,8)
b. (5,1,10,7,8) c.Error
c. Error
d. (5,1,2,7,8)
Quiz
3.What will be the output of the following:
d=dict()
d[(1,2,3)]=12
d[(4,5)]=20
print(d)
a. {1:12,2:12,3:12,4:20,5:20} b. {(1,2,3):12,(4,5):20)}
b. {(1,2,3):12,(4,5):20)}
c. Error
d. {1:12,2:24,3:36,4:80,5:100}
Quiz
4.What will be the output of the following:
cls={“EEE-A”: “Legends”,”EEE-B”:”Legends”}
print(cls[“Legends”])
a. EEE-A
b. Error
c. EEE-B b. Error
d. EEE-A,EEE-B
Quiz
5.What will be the output of the following:
capital={“Tamil Nadu”: “Chennai”,”Kerala”:”T.V.Puram”,”Karnataka”:”Bangalore”}
state=list(capital.values())
print(state)
a. Error d.
b. [“Tamil Nadu”,”Kerala”,”Karnataka”] [“Chennai”,”T.V.Puram”
,”Bangalore”]
c. {“Chennai”,”T.V.Puram”,”Bangalore”}
d. [“Chennai”,”T.V.Puram”,”Bangalore”]
Quiz
6.Which dictionary has been created correctly?
(i) d={1:[1,2],2:[2,4]}
(ii) d={[1,2]:1,[2,4]:2}
(iii)d={(1,2):1,(2,4):2}
(iv)d={1:”12”,2:”24”}
(v) d={“12”:1,”24”:2} d. i,iii,iv, and v
a. Only iv
b. Only ii
c. i,ii, and iii
d. i,iii,iv, and v
Summary
• Strings, lists, tuples, sets and dictionaries all deal with aggregates
• Two big differences
• Lists , Sets and dictionaries are mutable
• Unlike strings, tuples
• Strings, lists and tuples are ordered
• Unlike sets and dictionaries