Home > Software design >  How do you read a text file into a dictionary with the information on one line separated by '\
How do you read a text file into a dictionary with the information on one line separated by '\

Time:04-18

My text file reads like this: CSCI 160:4 CSCI 289:3 EE 201:4 MATH 208:3 (all in one line, separated by a tab '\t'). How do I read that text file into a dictionary with (key, val) separated at the ':'

CodePudding user response:

Try:

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)

Prints:

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

EDIT: To read from file, you can use this example (assuming your file has only one line):

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)
  • Related