'How do you read a text file into a dictionary with the information on one line separated by '\t' python
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 ':'
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
