Stripping string from rows in the text file and reading columns in the dictionary with lists as values

advertisements

I've been struggling a bit with getting my input file into the right format for my algorithm.

I want to read this text file:

1 -> 7,8
11 -> 1,19
219 -> 1,9,8

Into this dictionary:

{ 1: [7, 8], 11: [1, 19], 219: [1, 9, 8]}

I've tried this code:

with open("file.txt", "r+") as f:
    f.write(f.read().replace("->", " "))
    f.close()

d = {}
with open("file.txt") as file:
    for line in file:
        (key, val) = line.split()
        d[key] = val

But with this code it get's stuck on the fact that there are more than 2 arguments in the second column. How can make a list out of the elements in the second column and use that list as the value for each key?


There is no need to do that pre-processing step to remove the '->'. Simply use:

d = {}
with open("file.txt") as file:
    for line in file:
        left,right = line.split('->')
        d[int(left)] = [int(v) for v in right.split(',')]

You can even use dictionary comprehension and make it a one-liner:

with open("file.txt") as file:
    d = {int(left) : [int(v) for v in right.split(',')]
             for left,right in (line.split('->') for line in file)
        }

This gives:

>>> d
{1: [7, 8], 11: [1, 19], 219: [1, 9, 8]}