0

I have a file with items like this:-

0 -> 205,3
1 -> 0,110,18,49,8

I need to convert to a dictionary:-

{0:[205,3],
 1:[0,110,18,49,8]}

I tried:-

def read_input(filename):
    f = open(filename, 'r')
    g = defaultdict(list)
    for line in f:
        line = line.strip()
        line = line.split(' -> ')
        g[int(line[0])].append(line[1])
    return g

My result:-

defaultdict(list,
            {0: ['205,3'],
             1: ['0,110,18,49,8']})

I also tried:-

def read_input(filename):
    f = open(filename, 'r')
    g = defaultdict(list)
    for line in f:
        line = line.strip()
        line = line.split(' -> ')
        g[int(line[0])].append(int(x) for x in line[1].split(','))
    return g

Result:-

defaultdict(list,
            {0: [<generator object <genexpr> at 0x110e01410>],
             1: [<generator object <genexpr> at 0x110e01460>]})
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119
arjan-hada
  • 251
  • 3
  • 17
  • Not a duplicate. I checked ot the solutions and it doesn't help my case. Please elaborate more. – arjan-hada Nov 29 '15 at 18:12
  • Use can use the bultin `type` method to look at what data-type different objects are. The reason you have quotation marks is because your objects are strings -- because they were read in from a text file. You need to convert them to integers which is exactly what the other solution describes. You are *correctly* casting `line[0]` into an integer, but you are not casting `line[1]` into an integer --- it is still a string. – DilithiumMatrix Nov 29 '15 at 18:14
  • I tried the other solution and posted my result here. It didn't help me. – arjan-hada Nov 29 '15 at 18:15
  • You need to enclose your [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) in brackets for it to work right: `[int(x) for x in line[1].split(',')]`. It is a good procedure to try to understand the solutions you are implementing. – DilithiumMatrix Nov 29 '15 at 18:18
  • You should be using a [with](https://docs.python.org/2/reference/compound_stmts.html#with) statement to handle your file – kylieCatt Nov 29 '15 at 18:29

0 Answers0