Charlotte Grosjean
Charlotte Grosjean

Reputation: 5

Making a dictionary from a csv file with

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/catch 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.)

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.

Reminder about print with {} in your string: use print(string.format(variable)) to fill in the {} with your variable. If there are 2 {}'s, use .format(var1, var2)

This is what I got so far:

import csv

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.
    with open('mountains.csv', 'r') as handle:
        reader = csv.reader(handle, delimiter=',')
        
        for row in reader:
            name = row[0]
            height = row[1]
            int(height)
            
        dictionary = {name: height}
        
        for k,v in dictionary.items():
            print(k,v)
            return dictionary

And there's the csv file:

CSV

Upvotes: 0

Views: 996

Answers (2)

Moss
Moss

Reputation: 357

Don't forget to check if the file exists! I added an extra check so the function works with or without ".csv" file extension specified.

You also want to print a nice string using msg.format(name, height)

Lastly don't return the dictionary inside of the for loop! This ends your function and you will only see one message printed out.

For bonus points you can use csv.DictReader to read CSV files more efficiently. If the CSV does not have a header column, you need to pass fieldnames (i.e. name, height) yourself.

from csv import DictReader

def mountain_height(filename):
    msg = "The height of {} is {} meters."
    err_msg = "Error: File doesn't exist or is unreadable."
    if filename.split('.')[-1] != 'csv':
        filename += '.csv'
    try:
        open(filename)
    except FileNotFoundError:
        print(err_msg)
    with open(filename) as f:
        reader = DictReader(f, fieldnames=['name', 'height'], delimiter=',')
        mountain_heights = {
            row['name']: int(row['height']) for row in reader
        }
        for name, height in mountain_heights.items():
            print(msg.format(name, height))
        return mountain_heights

Upvotes: 0

Botje
Botje

Reputation: 30830

You're nearly there. You simply need to add an entry to mountains for each iteration of the loop:

mountains = dict()
with open('mountains.csv', 'r') as handle:
    reader = csv.reader(handle, delimiter=',')

    for row in reader:
        name = row[0]
        height = row[1]
        mountains[name] = int(height)

Upvotes: 1

Related Questions