1

I have an assignment to create a function loadResults where the number, time, name and surnames of the runners are stored, and returns a list of dictionaries with this information. The keys for the dictionary are: “number”, “name”, “surname”, “time”. So far I have:

def loadResults():


    myFile = open("marathon.csv", "r")

    number = []

    for line in myFile:

       info = line.split(',')
       s = {}
       s['number'] = info[0]
       s['time'] = info[1]
       s['firstname'] = info[2]
       s['surname'] = info[3:]
       number.append(s)

    myFile.close

    return number

however I then also have to write a function displayTime that receives the list of runners and the number of a runner and displays the name and the time. For which I have:

def displayTime(time,number,firstname):

    for s in number:
      if s['number'] == time:
        print(s['name'])


    runners = loadResults()
    displayTime(number,'3070')

Unfortunately I am not getting anywhere with this any help would be greatly appreciated.

3
  • Please correct your code formatting. Commented Nov 27, 2017 at 15:38
  • Can you please display some sample data? Commented Nov 27, 2017 at 15:45
  • Can you post your entire code? Maybe there is a mistake with your file opening (have you tried using the "with" method?) Commented Nov 27, 2017 at 15:53

1 Answer 1

1

You can use csv.DictReader:

import csv
with open('your_file') as csvfile:
    reader = csv.DictReader(csvfile)

Then reader is the dictionary.

If the csv file don't have the keys on the first row you can use fieldnames:

import csv
with open('your_file') as csvfile:
    reader = csv.DictReader(csvfile, fieldnames=['number', 'name', 'surname', 'time'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.