使用Python从.txt文件创建一个字典 [英] Creating a dictionary from a .txt file using Python
问题描述
如果您被赋予一个 .txt文件
,其中包含以下内容:
James Doe 2/16/96 IT210 A BUS222 B PHY100 C
John Gates 4/17/95 IT101 C MATH112 B CHEM123 A
Butch Thomas 1/28/95 CS100 C MATH115 C CHEM123 B
你如何得到它,所以它需要类名和成绩,并将它们放入一个空的字典,忽略其余的?我有代码设置来阅读 .txt文件
但被卡住了。任何建议?
这是我打开文件的代码:
def readFile():
new_dict = {}
myFile = open('Students.txt','r')
myFile中的行:
而不是为每个学生制作不同的变量,为什么不使用字典列表? >
请参阅以下代码:
>>> dictList = []
>>>在f:
元素= line.rstrip()。f($)
('Students.txt','r')作为f:
split()[3:]
dictList.append(dict(zip(elements [:: 2],elements [1 :: 2])))
>>> dictList
[{'IT210':'A','PHY100':'C','BUS222':'B'},{'IT101':'C','MATH112':'B' CHEM123':'A'},{'CS100':'C','CHEM123':'B','MATH115':'C'}]
如果您希望维护字典中txt文件中给出的顺序,请查看 OrderedDict
。
If you are given a .txt file
which contains these contents:
James Doe 2/16/96 IT210 A BUS222 B PHY100 C
John Gates 4/17/95 IT101 C MATH112 B CHEM123 A
Butch Thomas 1/28/95 CS100 C MATH115 C CHEM123 B
How can you get it so it takes the class names and grades and puts them into an empty dictionary while ignoring the rest? I have code set up to read the .txt file
but got stuck. Any suggestions?
This is my code for opening the file:
def readFile():
new_dict = {}
myFile = open('Students.txt', 'r')
for line in myFile:
Instead of making different variables for each student, why not use a list of dictionaries?
See the code below :
>>> dictList = []
>>> with open('Students.txt', 'r') as f:
for line in f:
elements = line.rstrip().split(" ")[3:]
dictList.append(dict(zip(elements[::2], elements[1::2])))
>>> dictList
[{'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}, {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}]
If you're looking to maintain the order as given in the txt file in the dictionary, then look into an OrderedDict
.
这篇关于使用Python从.txt文件创建一个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!