Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Esprit School of Business

Algorithmics, Data Structures


1st year LBC and Programming 2

Tutorial 3 : Tuples and dictionaries

Exercise 1
Given a list of tuples, write a python program to sort the tuples according to the second element
(item) of each tuple.
Examples:
Input : [('for', 24), ('Geeks', 8), ('Geeks', 30)]
Output : [('Geeks', 8), ('for', 24), ('Geeks', 30)]

Input : [('452', 10), ('256', 5), ('100', 20), ('135', 15)]


Output : [('256', 5), ('452', 10), ('135', 15), ('100', 20)]

Exercise 2
Given a list of tuples, delete all tuples of length K.

Examples :
Input : test_list = [(4, 5), (4, ), (8, 6), (1, ), (3, 4, 6, 7)], K = 2
Output : [(4, ), (1, ), (3, 4, 6, 7)]

Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 3
Output : [(4, 5), (4, ), (1, ), (3, 4, 6, 7)]

Exercise 3
What is the value of dictionary d at the end of the code below :
def init (d ) :
for x in d :
d [x]=0

d={’a’ : ’bbb’ , ’b’ : 15, (12 ,4) : [ ] }


init (d)
print(d)

Exercise 4

We have a dictionary that associates the first names of a company’s sales representatives with
the number of sales made by them. For example :

sales={"Dupont":14, "Alex":21, "Laurent":15, "Ivry":21}

1
Esprit School of Business
Algorithmics, Data Structures
1st year LBC and Programming 2

1) Write a function that takes such a dictionary as parameter and returns the total number
of sales in the company.
2) Write a function that takes such a dictionary as input and returns the first name of the
salesman which has the most sales. If several salesmen are equals on the criterion, the
function should return the first name of one of them.

Exercise 5

Write a function that takes as input a dictionary that associates to a name a list of grades and
returns the list of names of people with the highest average (if there are equals, this list will
several elements, otherwise it will contain only one) and the corresponding average. You can
use the following dictionary to test the function :

grades = {"Tom": [8, 10, 12], "Mila": [10, 9], "Alex": [], "Lina": [12, 10, 8]}

Exercise 6

Write a function that takes as input a list of dictionaries and returns a dictionary merging the
information from these dictionaries as follow : for each key present in at least one dictionary,
the associated value will be the list of values associated with this key in the dictionaries passed
as parameter the the function.

For example, for the following dictionaries :

dict1 = {"a": 1, "d": 4, "g": 7}


dict2 = {"a": 1, "b": 2, "h": [8]}
dict3 = {"a": 2, "c": 3, "h": 9}

The function should return :

{'a': [1, 1, 2], 'd': [4], 'g': [7], 'b': [2], 'h': [[8], 9], 'c': [3]}

You might also like