Exercice 84
1) - Ecrire un programme en Python qui prend en entrée une liste de dictionnaires qui contient les données des étudiants et classe la liste par ordre alphabétique selon les noms des étudiants.
Traiter l'exemple du dictionnaire suivant:
1 2 3 4 5 |
data_students = [{'nom': 'Walid', 'age': 22, 'section': 'Math'}, {'nom': 'Nathalie', 'age': 20, 'section': 'SVT'}, {'nom': 'Hafid', 'age': 19, 'section': 'Informatique'}, {'nom': 'Adam', 'age': 21, 'section': 'HG'}, {'nom': 'Racha', 'age': 19, 'section': 'Sc Eco'}] |
2) - Ecrire un autre programme qui enregistre les données dans un fichier texte nommé 'data_students.txt'
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
from operator import itemgetter def trier_par_nom(liste_etudiants): liste_etudiants.sort(key=itemgetter('nom')) return liste_etudiants def enregistrer_dans_fichier(liste_etudiants, nom_fichier='data_students.txt'): with open(nom_fichier, 'w') as fichier: for etudiant in liste_etudiants: ligne = f"Nom: {etudiant['nom']}, Age: {etudiant['age']}, Section: {etudiant['section']}\n" fichier.write(ligne) # Exemple d'utilisation avec le dictionnaire fourni data_students = [{'nom': 'Walid', 'age': 22, 'section': 'Math'}, {'nom': 'Nathalie', 'age': 20, 'section': 'SVT'}, {'nom': 'Hafid', 'age': 19, 'section': 'Informatique'}, {'nom': 'Adam', 'age': 21, 'section': 'HG'}, {'nom': 'Racha', 'age': 19, 'section': 'Sc Eco'}] resultat_trie = trier_par_nom(data_students) # Enregistrer les données triées dans le fichier 'data_students.txt' enregistrer_dans_fichier(resultat_trie) print("Données enregistrées dans 'data_students.txt'") """ Output: {'nom': 'Adam', 'age': 21, 'section': 'HG'} {'nom': 'Hafid', 'age': 19, 'section': 'Informatique'} {'nom': 'Nathalie', 'age': 20, 'section': 'SVT'} {'nom': 'Racha', 'age': 19, 'section': 'Sc Eco'} {'nom': 'Walid', 'age': 22, 'section': 'Math'} Données enregistrées dans 'data_students.txt' """ |
Après exécution vous allez constater la création d'un fichier 'data_students.txt' qui contient les données suivantes:
Nom: Adam, Age: 21, Section: HG
Nom: Hafid, Age: 19, Section: Informatique
Nom: Nathalie, Age: 20, Section: SVT
Nom: Racha, Age: 19, Section: Sc Eco
Nom: Walid, Age: 22, Section: Math
Younes Derfoufi
CRMEF OUJDA
Acheter sur Très Facile !
-
Guide Raspberry Pi - Pas à pas pour débutant
€ 14,00 Acheter le livre -
Apprendre Raspberry Pi : Série pour les Nuls 2ème édition
€ 24,00 Acheter le livre -
Promo !
TP-Link Routeur WiFi 6 Archer AX18** WiFi 6 nouvelle génération
Le prix initial était : € 40,00.€ 35,00Le prix actuel est : € 35,00. Acheter le produit