In my project, I’m trying to go through a file that has many strings and split them. There are multiple lines. I want each portion of the split string to go into a dict, but I’m not sure if that’s possible. Right now I have:
while inFile:
key, value = inFile.readline().lower().rstrip().rsplit(' ', 1)
I thought about using dict and zip, but I think that’s if you have lists..
My input file looks like this. The ‘$’ are end lines. I’d like for example, ‘A B’ to be the key, and ’10’ to be the value.
A B 10 $
A C 4$
B D 29$
B E 1 $
You should be able to do something like the following:
This works because
dict()can accept an iterable of key/value pairs, and as long as each line in your file contains at least one space,line.lower().rstrip().rsplit(' ', 1)will result in a two-element tuple.Note that iterating over a file object will give you each line in the file, so
for line in inFile:is preferred overwhile inFile: line = inFile.readline().