subject_dic = {}
inputFile = open(filename)
for line in inputFile:
split_line = string.split(line, ',')
subject_dic[split_line[0]] = tuple(split_line[1:3])
print subject_dic
I'm getting
{'6.08': ('1', '10\n'), '6.09': ('3', '7\n'), '6.19': ('8', '19'), '6.10': ('8', '18\n'), '6.00': ('10', '1\n'), '6.01': ('5', '4\n'), '6.02': ('5', '6\n'), '6.03': ('2', '9\n'), '6.04': ('1', '2\n'), '6.05': ('1', '18\n'), '6.06': ('5', '19\n'), '6.07': ('2', '10\n'), '6.13': ('9', '16\n'), '6.18': ('10', '4\n'), '6.15': ('10', '6\n'), '6.16': ('6', '9\n'), '6.12': ('6', '3\n'), '6.17': ('9', '3\n'), '6.14': ('10', '8\n'), '6.11': ('6', '8\n')}
but I don't know how to remove '\n'
from the ends of my tuples. This is really simple but I can't find out how to do this. It's because I'm reading vertically from a file (hence the newline) but I don't want that '\n'
in my dictionary.
Thanks!
split_line = split_line.strip()
See here.
If you're not working with a ridiculously large file, you can actually avoid having to use .strip()
at all. If you read in the entire file as a string using .read()
and then perform .splitlines()
on that string.
Here is an example. I commented out your code where I changed things. I changed the example not to use slicing in exchange for explicit variable assignment.
subject_dic = {}
inputFile = open(filename)
# Turn "line1\nline2\n" into ['line1', 'line2']
inputData = inputFile.read().splitlines()
#for line in inputFile:
for line in inputData:
#split_line = string.split(line, ',')
#subject_dic[split_line[0]] = tuple(split_line[1:3])
mykey, myval1, myval2 = line.split(',') # Strings always have .split()
subject_dic[mykey] = (myval1, myval2) # Explicit tuple assignment
print subject_dic
Outputs:
{'6.00': ('10', '1'),
'6.01': ('5', '4'),
'6.02': ('5', '6'),
'6.03': ('2', '9'),
'6.04': ('1', '2'),
'6.05': ('1', '18'),
'6.06': ('5', '19'),
'6.07': ('2', '10'),
'6.08': ('1', '10'),
'6.09': ('3', '7'),
'6.10': ('8', '18'),
'6.11': ('6', '8'),
'6.12': ('6', '3'),
'6.13': ('9', '16'),
'6.14': ('10', '8'),
'6.15': ('10', '6'),
'6.16': ('6', '9'),
'6.17': ('9', '3'),
'6.18': ('10', '4'),
'6.19': ('8', '19')}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With