Skip to content Skip to sidebar Skip to footer

Convert List Of Values From A Txt File To Dictionary

So i have this txt file called 'Students.txt', I want to define a function called load(student) so i have this code: def load(student): body im not quite sure what to write

Solution 1:

Looks like a CSV file. You can use the csv module then:

import csv
studentReader = csv.reader(open('Students.txt', 'rb'), delimiter=',', skipinitialspace=True)
d = dict()
for row in studentReader:
    d[row[0]] = tuple(row[1:])

This won't give you the year as integer, you have to transform it yourself:

for row in studentReader:
    d[row[0]] = tuple(row[1], int(row[2]))

Solution 2:

Something like this should do it, I think:

students = {}

infile = open("students.txt")
for line in infile:
  line = line.strip()
  parts = [p.strip() for p in line.split(",")]
  students[parts[0]] = (parts[1], parts[2])

This might not be 100%, but should give you a starting-point. Error handling was omitted for brevity.


Solution 3:

def load(students_file):
    result = {}
    for line in students_file:
        key, name, year_of_birth = [x.strip() for x in line.split(",")]
        result[key] = (name, year_of_birth)
    return result

Solution 4:

I would use the pickle module in python to save your data as a dict so you could load it easily by unpickling it. Or, you could just do:

d = {}
with open('Students.txt', 'r') as f:
  for line in f:
    tmp = line.strip().split(',')
    d[tmp[0]] = tuple(tmp[1],tmp[2])

Post a Comment for "Convert List Of Values From A Txt File To Dictionary"