0% found this document useful (0 votes)
17 views26 pages

3 - Tuples and Dictionaries

Uploaded by

ghassenchich
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)
17 views26 pages

3 - Tuples and Dictionaries

Uploaded by

ghassenchich
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/ 26

Module: ADSP2 1st year LBC

2022 - 2023
Plan
I. Tuples

II. Dictionaries

2
I. Tuples

3
Tuples
 A tuple is an unmodifiable sequence of elements that can be homogeneous (of
the same type) or heterogeneous (of different types)

 Several possible declarations of tuples :


 t = 'a','b',2
 t = ('a', 'b', 2)

 There are situations where parentheses are required, such as when you want an empty
tuple or when there is possible ambiguity.
 tuple with 0 elements : t = ()
 tuple with 1 element : t = ('a',) or t = 'a', with the comma in both cases !
 tuple with 2 elements : t = ('a', 'b') or t = 'a', 'b‘
 A nested tuple (a tuple of tuples) : u = t, (1, 2, 3, 4, 5)
Tuples
 Access :
 t = 12345, 54321, 'hello!'
 t[0]
12345

 Assignment not permitted :


 t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
Tuples
Example:
Consider the function sum which sums the elements of a tuple of integers:

def sum(values) :
s=0
i=0
while i < len(values):
s += values[i]
i += 1
return s
Tuples
 Use of tuples : They can be used as keys in dictionaries, but lists cannot. Tuples also
take slightly less memory than lists. On the other hand, it is easier to add, delete, insert
in a list than in a tuple.

 Another use of the tuple is that it allows to define functions that return several values
in the form of a tuple.
def Find(data, element):
i=0
while i < len(data):
if data[i] == element:
return True, i
i += 1
return False, None
Tuples
For example the following two calls of the previous function :
values = [1, 2, 3, 4]
print(Find(values, 2))
print(Find(values, 6))

produces the following results :


(True, 1)
(False, None)

In this example, we display the result with a print. So it's no problem to have
two different data types in return value.
Tuples
Similarly, we could store the return value of the function in a variable:

result = Find(values, 2)

A tuple could be constructed from simple elements. It is also possible to do the


reverse operation, i.e. assign each element of a tuple to a different variable:

find, pos = Find(values, 2)


Tuples
 You can therefore modify the value of several variables at the same time. This is
called a multiple assignment.

 Example :
barcode, name, price = 544996, "Coca-Cola", 0.70

 The assignment of the three variables takes place simultaneously. This feature
makes it very easy to swap the values of two variables, using the following
statement:
x, y = y, x
Tuples
The following manipulations of tuples are done in the same way as lists and
strings:
 Iterating through the values of a tuple • Convert any type of sequence (lists, strings, dictionaries)
for item in t : to tuple
print(item) L = [1, 2, 3]
 Length of a tuple s = "abc"
len(t) t = tuple(L) #t takes then (1,2,3)
 Slicing a tuple (sub-tuple)
t1 = tuple(s) #t1 takes then (‘a’, ‘b’, ‘c’)
t[si:ei]
 Membership test
if item in t:
….
 Tuples concatenation
t2 = (1,2,3) + (4,5,6) #t2 takes (1,2,3,4,5,6)
Application 1
A point is characterized by its X and Y coordinates. Create by assignment,
the points A(-1, 0.9) and B(2.5, 6) represented by tuples and display them in
the following form:
Point A: X = value, Y = value

A = (-1,0.9)
B = (2.5, 6)
print("Point A : X =",A[0],", Y =",A[1])
print("Point B : X =",B[0],", Y =",B[1])
Application 2
An employee is characterized by his:
 Registration number (integer)
• Name (string)
• Salary (real)
• Marital status (‘M’ or ‘S’)

Write a program that allows:


• To create an Emp list which will contain information on the 50 employees of
a company. Employee information is stored in a tuple.
• Display the number of married employees whose salary is <= 600 dinars.
Application 2
Emp=[]
n = 50
for i in range(0,n):
print("Information of employee",i+1, ":")
rn = int(input("Registration number: "))
name = input("Name: ")
sal = float(input("Salary: "))
ms = ""
while ms not in ["M","S","m","s"]:
ms = input("Marital status(M/S): ")
emp = (rn,name,sal,ms.upper())
Emp.append(emp)
print(Emp)
count = 0
for i in range(0,n):
if Emp[i][2]<= 600 and Emp[i][3]=='M':
count+=1
print("Number of married employees whose salary <=600:",count)
Application 3
A student is characterized by a set of information items (student card number, name, 3 marks, final grade). Consider that the
information items of each student are stored in a tuple, a class students are stored within a list (list of tuples).

1) Write a procedure INPUT(L,N) which allows to enter the information items of N students, the final grade is the average
of the three given marks, then stores them in the list of tuples L.

2) Write a procedure DISPLAY(std) which displays the information items of a student stored within the tuple std.

3) Write a function SEARCH(L,SCN) which allows to search for a student information items within a list L using his student
card number SCN and returns its position within the list if found, -1 else.

4) Write an AVGRADE(L) function that is used to calculate the general average of the students whose information items are
stored within the list L.

5) Write a main program that allows to test the above procedures and functions, by filling a list of students information
within a class, displaying their information items, searching for a student with given student card number, displaying his
information items if found, and calculating the general average of the class.
Application 3
def INPUT(L,N): def SEARCH(L,SCN):
for i in range(N):
print("Information of student",i+1, ":") pos = -1
scn = input("Student card number: ") i = 0
name = input("Name: ") while i<len(L) and pos == -1:
m1 = float(input("Mark 1: "))
m2 = float(input("Mark 2: ")) if L[i][0]==SCN:
m3 = float(input("Mark 3: ")) pos = i
fg= (m1 + m2 + m3)/3 else:
std= (scn,name,m1,m2,m3,fg)
L.append(std) i+=1
return pos
def DISPLAY(std):
print("Student card number:",std[0])
print("Name:",std[1]) def AVGRADE(L):
print("Mark 1:",std[2]) s=0
print("Mark 2:",std[3])
for i in range(0,len(L)):
print("Mark 3:",std[4])
print("Final grade:",std[5]) s+= L[i][5]
return s/len(L)
Application 3
Class = []
N = int(input("Enter the number of students in the class: "))
INPUT(Class,N)
for i in range(N):
print("Information of student",i+1)
DISPLAY(Class[i])
print("The average class grade", AVGRADE(Class))
scn = input("Enter the student card number to search for ")
p=SEARCH(Class,scn)
if p==-1:
print("Student not found")
else:
print("Student found")
DISPLAY(Class[p])
II. Dictionaries

18
Dictionaries
 Dictionaries : An unordered (no indexes) set of comma-separated pairs of key :
value. Dictionaries are indexed by keys (key values are unique within a dictionary).
Keys could be any non-mutable type :
 Integer
 Reel
 String
 Boolean
 a tuple whose elements are non-mutable

Remark : A dictionary could have a key set to None (but of course only one).
Dictionaries
 Declaration and initialization :
d = {} : initialization to an empty dictionary.
#We can also use: d = dict().
d = {‘abc': 1, ‘cde': 2} : initialization.

 We can also define a dictionary with a list of pairs of 2-valued tuples:


d = dict([('a', 1), ('b', 2)])
Dictionaries
 Elementary manipulations :
d[‘abc'] = 5 : assignment of the value 5 to the key ‘abc’ in the dictionary d

del d[‘cde'] : deleting a key, and its value from a dictionary d

‘abc' in d : tests the membership of a key to a dictionary d

‘efg' not in d : tests the non membership of a key to a dictionary d

len(d) : returns the number of items within a dictionary d


Dictionaries
 Other predefined functions used with dictionaries:

d.clear() : deletes all items

d.copy() : creates a copy of d

d.get(key) : returns the value if the key is found, None else.

d.items() : an iterator on the dictionary returns the tuple with the pairs (key, value).

d.keys() an iterator on the dictionary keys. If the list of keys is nedded list(d.keys())

d.values() : an iterator on the dictionary values

d.pop(key) : removes the key and returns the value (KeyError if key does not exist)
Dictionaries
 To iterate through the dictionary keys :
for x in d:
print(x)

 To iterate through a dictionary while retrieving the keys and values at the same
time:
for k, v in d.items():
print(k,' : ' ,v)
Application 5
Resume Application 2 with Emp being a dictionary having:

- As a key, the registration number

- As a value, the tuple with the remaining information.

Emp={}
n = 50
for i in range(n):
print("Information of employee",i+1, ":")
rn = int(input("Registration number: "))
name = input("Name: ")
sal = float(input("Salary: "))
ms = ""
while ms not in ["M","S","m","s"]:
ms = input("Marital status(M/S): ")
emp = (name,sal,ms.upper())
Emp[rn]=emp
print(Emp)
count = 0
for rn in Emp:
if Emp[rn][2]<=600 and Emp[rn][3]=='M':
count+=1
print("Number of married employees whose salary <=600:",count)
Application 6
A student is characterized by a set of information items (student card number, name, 3 marks, final grade). Consider that the
information items of students are stored in a dictionary, where the registration number represents the key, and the
remaining information items are stored within a list that represents the value (Dictionary of lists).

1) Write a procedure INPUT(D,N) which allows to enter the information items of N students, the final grade is the average
of the three given marks, then stores them in the dictionary of lists D.

2) Write a procedure DISPLAY(SCN,l) which takes as parameters the student card number SCN and a list of the rest of the
information l of a student then displays his information items.

3) Write an AVGRADE(D) function that is used to calculate the general average of the students whose information items are
stored within the dictionary D.

4) Write a main program that allows to test the above procedures and functions, by filling a dictionary of students
information within a class, displaying their information items, searching for a student with given student card number,
displaying his information items if found, and calculating the general average of the class.
Important !
Lists, dictionaries and tuples are entities that can contain complex types. We
can therefore build lists that contain dictionaries, tuples or other lists, but also
dictionaries containing tuples, lists, etc.

You might also like