Exercice python dictionary

Fermé
will - 10 févr. 2022 à 15:39
jee pee Messages postés 40478 Date d'inscription mercredi 2 mai 2007 Statut Modérateur Dernière intervention 27 novembre 2024 - 10 févr. 2022 à 16:46
Bonjour à tous,
je cherche à écrire une fonction qui à partir d'un fichier csv va créer un dictionnaire, pour après faire ressortir les informations utiles de ce dictionnaire. Je suis novice et j'ai bcp de mal avec l'utilisation des dictionnaires, des "items" etc en python, j'ai donc écrit qqchose qui fonctionne mais sans utiliser de dictionnaire..

def mountain_height(filename):
""" Read in a csv file of mountain names and heights.
Parse the lines and print the names and heights.
Return the data as a dictionary.
The key is the mountain and the height is the value.
"""

mountains = dict()
msg = "The height of {} is {} meters."
err_msg = "Error: File doesn't exist or is unreadable."

# TYPE YOUR CODE HERE.
try:
with open('mountains.csv', 'r') as handle:
for line in handle:
mountains = line.split(",")
print("The height of " + mountains[0] + " is " + mountains[1] + " meters.")
except:
print("Error: Something wrong with your file location?")
return

return mountains


Et voici les consignes de mon exercice :
Create a function that takes a file name (and path if needed) as the argument. In the function, open and read in the file mountains.csv. Use a try/except to be sure the file exists and is readable. If the file location is wrong or it can't be opened, print an error that begins with "Error:". (You can test it with a junk path or filename that doesn't exist.)

The pattern I suggest for this is:

try:
with open('mountains.csv', 'r') as handle:
for line in handle:
#....do stuff here (you can have other try/except in here if you want)
except:
print("Error: Something wrong with your file location?")
return


Mountains.csv is a comma-separated list of mountains, their height in meters, and the range they belong to. (Look at it in a text editor, but don't edit/modify the file!) A CSV file is a common format for raw data. Other types of raw data files are point-virgule (semi-colon) separated files or tab-separated files. However the columns are separated, you must use that character in your "split" code.

In this case, it's a comma. Split each line by the comma, and make a dictionary where the key is the mountain name (the first element) and the height is the value, the second element. Make sure to convert the height to a number. Then print the keys and values of the dictionary using .items(), in readable sentences that say, for instance, "The height of K2 is 8611 meters." Return the dictionary at the end of the function.


Merci à ceux qui pourront m'aider !

1 réponse

jee pee Messages postés 40478 Date d'inscription mercredi 2 mai 2007 Statut Modérateur Dernière intervention 27 novembre 2024 9 428
Modifié le 10 févr. 2022 à 16:47
Bonjour,

Voilà quelques instructions de base sur les dictionnaires que tu pourrais étudier et intégrer dans ton programme :

mountains = {}
mountains = {'K2': 8611, 'Mont-Blanc': 4807, 'Everest': 8849}
mountains ["Aconcagua"]=6959
print(mountains)
print(mountains['K2'])

for key, value in mountains.items():
        print("The height of",key,"is",value,"meters.")




0