How do I split on the second " , "

Viewed 119

I am trying to split on the second,

file = open()
dictionary = {}
for linje in filen:
    bites = linje. split()
    month = bites[0]
    temp = bites[0]
    dictionary[month] = temp
print(dictionary)

The file looks like this:

Jan,1,2.7
Jan,2,2.8
Jan,3,0.7
Jan,4,1.8
Jan,5,1.2
...... each day every day of the year.

If I write split(",") the output becomes this in my dictionary:

{Jan : Jan}.

If I don't split it becomes like this:

{Jan,1,2.7 : Jan,1,2.7}

I want it to be like this:

{Jan,1: 2.7}
4 Answers

You can split from the right and specify how many splits to have:

with open('file_name') as filen:
    dictionary = {}
    for linje in filen:
        month, value = linje.rsplit(',', maxsplit=1)
        dictionary[month] = value
    print(dictionary)

Sidenote: I suggest opening files as a context manager, i.e. with with statement.

Split once with rsplit.

>>> part1, part2 = 'Jan,3,0.7'.rsplit(',', maxsplit=1)
>>> part1
'Jan,3'
>>> part2
'0.7'

I would've go with the 'rsplit' solutions above me, but here's a solution with normal split:

file = open()
dictionary = {}
for linje in filen:
    digit,temp= linje[4:].split(',')
    month = linje[:4] # Months are represented by 3 chars. (4, including the comma)
    dictionary[month+digit] = temp #concat the digit to the month
print(dictionary)
file = '''Jan,1,2.7
Jan,2,2.8
Jan,3,0.7
Jan,4,1.8
Jan,5,1.2'''
file = file.split('\n')

keys = []
keysdata = []
for i in range(len(file)):
    files = file[i].split(',')
    keys.append(f'{files[0]}, {files[1]}')
    keysdata.append(float(files[2]))
dictionary = dict(zip(keys, keysdata))

print(dictionary)

Output:

{'Jan, 1': 2.7, 'Jan, 2': 2.8, 'Jan, 3': 0.7, 'Jan, 4': 1.8, 'Jan, 5': 1.2}
Related