python创建一个txt文件-使用Python从.txt文件创建一个字典

1586010002-jmsa.png

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.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值