convert list of values from a txt file to dictionary

走远了吗. 提交于 2019-12-11 01:52:34

问题


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 for the body of code so that it reads the file and returns the value from the file as dictionary. I know it would be something like readlines() anyway, the file students.txt looks like this:

P883, Michael Smith, 1991
L672, Jane Collins, 1992
(added)L322, Randy Green, 1992
H732, Justin Wood, 1995(added)
^key  ^name        ^year of birth 

the function has to return as a dictionary that looks like this:

{'P883': ('Michael Smith',1991),
'(key)':('name','year')}

I managed to return the values by trial and error however i cant make new lines and keep returning \n.

=============== this question has been answered and i used the following code which works perfectly however when there is a space in the values from the txt file.. (see added parts) it doesnt work anymore and gives an error saying that list index is out of range


回答1:


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.




回答2:


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]))



回答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



回答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])


来源:https://stackoverflow.com/questions/5472238/convert-list-of-values-from-a-txt-file-to-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!