将值从txt文件转换为字典 [英] convert list of values from a txt file to dictionary

查看:166
本文介绍了将值从txt文件转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个名为students.txt的txt文件,我想定义一个名为load(student)
的函数,所以我有这个代码:

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

我不太确定要为代码正文写什么,以便它读取文件并从文件中返回值作为字典。我知道这会像readlines()
,文件students.txt看起来像这样:

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.

===============
这个问题已经回答了,我使用了以下代码,但是,在txt文件中的值中有一个空格(参见添加的部分)它不再工作,并给出一个错误,表示列表索引超出范围

=============== 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

推荐答案

这样做应该这样做,我想:

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

这可能不是100%,但应该给你一个起点。为简洁起见,省略错误处理。

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

这篇关于将值从txt文件转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆