3 - Tuples and Dictionaries
3 - Tuples and Dictionaries
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)
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
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))
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)
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’)
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.
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.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:
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.