0% found this document useful (0 votes)
37 views61 pages

U18CSI2201 - Unit 4 Tuples and Dictionaries 1

Uploaded by

shriaarthy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views61 pages

U18CSI2201 - Unit 4 Tuples and Dictionaries 1

Uploaded by

shriaarthy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

U18CSI2201 - PYTHON PROGRAMMING

UNIT – IV

Tuples and Dictionaries


Learning Objectives
• After undergoing this course the student able to
Source of Content
• http://nptel.ac.in
• https://
www.edx.org/course?search_query=Computing+in+Python+III%3A+D
ata+Structures
• https://www.w3resource.com/python/python-tutorial.php
Grading
Tuples
Need for Tuple

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

• Alternate method is by assigning a tuple value to a variable.


Eg:
T1=() #Creates an Empty tuple
T2=(1,2,3,4) #Equivalent to T2=tuple(1,2,3,4)
Inbuilt python functions for Tuple
Example:
>>>a=(4,6,1,19,2,3)
>>>len(a) #return length
6
>>>min(a) #return smallest value
1
>>>max(a) #return largest value
19
Inbuilt python functions for Tuple
Example:
>>>t=(“APPLE”)
>>>t.index(‘A’) #return index position
0
>>> t.count(‘P’) #return the count of given character
2
Index[] operator in tuple
• Since tuples are like lists the indexing and slicing of tuples is also similar
to that lists.
• First character is stored at 0th position and last character is stored at a
position one less than that of the length of the string.

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

• (11) is a perfectly acceptable expression


• (11) without the comma is the integer 11
• (11, ) with the comma is a tuple containing the integer 11
Tuples are immutable
>>> mytuple = (11, 22, 33)
>>> saved = mytuple
>>> mytuple += (44,) # new tuple created and stored in different id
>>> mytuple
(11, 22, 33, 44)
>>> saved
(11, 22, 33)
Sorting tuples
>>> atuple = (33, 22, 11)
>>> atuple.sort()
Traceback (most recent call last):

AttributeError:
'tuple' object has no attribute 'sort' Tuples are immutable!
>>> atuple = sorted(atuple)
>>> atuple
[11, 22, 33] sorted( ) returns a list!
Most other things work!
>>> atuple = (11, 22, 33)
>>> len(atuple)
3
>>> 44 in atuple
False
>>> [i for i in atuple]
[11, 22, 33]
Converting lists and strings into tuples
>>> alist = [11, 22, 33]
>>> atuple = tuple(alist)
>>> atuple
(11, 22, 33)
>>> newtuple = tuple('Hello World!')
>>> newtuple
('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!')
zip() function
• zip() is an inbuilt function.
• Takes items in sequence from a number of collections to make a list of
tuples, where each tuple contains one item from each collection.
• Used to group items from a list which has the same index.
Example
>>>A1=[1,2,3] Note: If sequences are not of
>>>A2=“xyz” the same length, then the
result of zip() has the length of
>>>list(zip(A1,A2)) #Zip list A1 and A2
the shorter sequence.
[(1, 'x'), (2, 'y'), (3, 'z')]
Inverse zip(*) function
* operator is used within the zip() which unpacks a sequence into positional
arguments.
Example:

x=[("HP",34000),("DELL", 26000),("APPLE",75000)] #list of tuples


laptop,price=zip(*x)
print(laptop)
print(price)

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.items() #returns a sequence of tuples


dict_items([ ('Alice', 25), ('Carol', 'twenty-two')])

>>> age.keys() # returns a sequence of keys


dict_keys([ 'Alice', 'Carol'])

age.values() # returns a sequence of values


dict_values([25, 'twenty-two'])
Creating Dictionaries
To create a student dictionary Output:
Enter no. of students:2
student = dict()
n=int(input("Enter no. of students:")) Enter roll:101

for i in range(0,n): Enter name:anitha


roll = input("Enter roll:") Enter roll:102
student[roll]=input("Enter name:") Enter name:sindhu
print(student)
{'101': 'anitha', '102': 'sindhu'}
Updating dictionaries
>>> age = {'Alice': 26 , 'Carol' : 22}
>>> age.update({'Bob' : 29})
>>> age
{'Bob': 29, 'Carol': 22, 'Alice': 26} # if key not exists , item is inserted
>>> age.update({'Carol' : 23})
>>> age
{'Bob': 29, 'Carol': 23, 'Alice': 26} #if key exists, value is updated
Returning a value
>>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26}
>>> age.get('Bob') #returns the value for the key
29
>>> age['Bob']
29
Removing a specific item
>>> a = {'Alice' : 26, 'Carol' : 'twenty-two'}
>>> a
{'Alice': 26, 'Carol': 'twenty-two'}
>>> a.pop('Carol’) #removes a key and returns the value if the key exists
'twenty-two'
>>> a
{'Alice': 26}
Removing all the items
>>> a = {'Alice' : 26, 'Carol' : 'twenty-two'}
>>>a.clear() #removes all the keys
>>> a
{}
Remove a random item
>>> age = {'Bob': 29, 'Carol': 23, 'Alice': 26}

>>> 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'}

for key,val in likes.items():


print(key,"likes",val)

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'}

for val in likes.values():


print(val)

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'}

num=input("Enter octal number for conversion:")


oct=oct_bin(num,oct_bin_table)
print("Given octal number in binary is:",oct)
Nested Dictionaries
A Dictionary within a dictionary is called nested dictionary

Example :

>>> movies={"TITANIC": {"Hero":"Leonardo DiCaprio","Director":"James


Cameron"},"GODZILLA":{"Hero":"Aaron Taylor","Director":"Gareth Edwards"}}

>>> 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.

2. Write a program that acts as a currency convertor. Various currency


equivalent for one Indian rupee is to be stored in a dictionary initially (eg.
"US dollar":0.014,"Brazilian Real":0.055,"Singapore dollar":0.02 etc.). The
program should input the quantity Indian rupees you have and required
currency. It should print the equivalent value of given currency referring the
dictionary .
Input: Enter the Indian rupees: 1000
Enter the currency: US dollar
Output: 1000 X 0.014 =14.00
Solution for Ex.1
def print_count(alist):
d = {'p' : 0, 'z' : 0, 'n' : 0}
for digit in alist:
if digit >0:
d['p'] += 1
Output:
elif digit == 0: {'p': 4, 'z': 2, 'n': 3}
d['z'] += 1
else:
d['n'] += 1
return d

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

Enter the name of currency: US dollar


x=currency.get(curr)
final=rupee*x Indian money value for given currency: 14.0

print("Indian money value for given currency:",final)


Polynomials as Dictionaries
• Keys in a dictionary are not restricted to be strings.
• Let us see how dictionaries with integers as keys represent a
polynomial.
• P(Y)=-2+Y2+3Y6
• All terms can be viewed as set of power and coefficient terms.
• Eg. First term ie -2 contains power of y as 0 and coefficient as -2.
Similarly third term has coefficient as 3 and power of y as 6.
Representing polynomial as Dictionaries
and Lists
P(Y)=-2+Y2+3Y6 can be represented as

P={0:-2,2:1,6:3} #using dictionary

P=[-2,0,1,0,0,0,3] #using lists


Program to evaluate a polynomial of one
variable i.e x if the value of x is 2.
• P(X)=-2+X2+3X3
• P(2)=26
def eval_poly(p,x):
sum=0
for pow in p:
sum=sum+p[pow]*x**pow
print("value of polynomial after evaluation:", sum)
p={0:-2,2:1,3:3}
eval_poly(p,2)
Output:
value of polynomial after evaluation: 26
Quiz
1.What will be the output of the following:
t=()
print(t.__len__())

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

You might also like