你如何将一个文本文件读入字典,其中一行中的信息由 '\t' python 分隔

How do you read a text file into a dictionary with the information on one line separated by '\t' python

我的文本文件是这样写的: CSCI 160:4 CSCI 289:3 EE 201:4 MATH 208:3(全部在一行中,由制表符 '\t' 分隔)。我如何将该文本文件读入字典,其中 (key, val) 在 ':'

处分隔

尝试:

s = "CSCI 160:4\tCSCI 289:3\tEE 201:4\tMATH 208:3"

d = dict(item.split(":") for item in s.split("\t"))
print(d)

打印:

{"CSCI 160": "4", "CSCI 289": "3", "EE 201": "4", "MATH 208": "3"}

编辑:要从文件中读取,您可以使用此示例(假设您的文件只有一行):

with open("your_file.txt", "r") as f_in:
    s = f_in.read().strip()

d = dict(item.split(":") for item in s.split("\t"))
print(d)