Trying to create a dictionary but don't know how to deal with \ n

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 get

 {'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 the '\n' from the ends of my tuples. It is really simple, but I cannot figure out how to do it. This is because I am reading vertically from a file (hence in a new line), but I do not want '\n' in my dictionary.

Thanks!

+4
source share
5 answers

If you are not working with a ridiculously large file, you may not use .strip() at all. If you read the entire file as a line using .read() , then do .splitlines() on that line.

Here is an example. I commented on your code where I made a difference. I changed the example so as not to use a slice in exchange for an explicit assignment of variables.

 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')} 
+2
source
 split_line = split_line.strip() 

See here .

+6
source

Use strip on lines to crop new lines.

str.strip ([characters])

Returns a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to remove. If omitted or None, the chars argument removes spaces by default. The chars argument is not a prefix or suffix; rather, all combinations of its meanings are devoid of:

+1
source
 line = line.strip() 

at the beginning of the cycle.

+1
source

This should work:

 subject_dic = {} inputFile = open(filename) for line in map(lambda x: x.strip(), inputFile): split_line = string.split(line, ',') subject_dic[split_line[0]] = tuple(split_line[1:3]) print subject_dic 
0
source

All Articles