0

If I have a file that has a content of this kind:
a,b
c,d
e,f
g,h

I need to make a list of the letters in the first column, i.e., [a, c, e, g]. I wrote some code which prints these letters but I don't know how to put them into a list. Here is the code:

def file_to_dict(f):
    for line in f:
        columns = line.split(",")
        print columns[0]

Your help is appreciated.

4
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by snippsat
0

Hint:

>>> l = []
>>> l += [ "a" ]
>>> l
['a']
>>>

:)

I did the following

def file_to_dict(f):
    list1 = []
    for line in f:
        columns = line.split(",")
        letters = columns[1]
    list1 += [letters]
    print list1

but the output is just . It always prints only the last letter. How to print them all in a list?

0

hi again,
the problem is that you have to add the letter in the list while you are in the for loop :)

for line in f:
    columns = line.split(",")
    letters = columns[ 0 ]
    list1 += [ letters ]

also I am not sure why you put columns[ 1 ], I thought you wanted the first element, which is columns[ 0 ] :)

0

hi again,
the problem is that you have to add the letter in the list while you are in the for loop :)

for line in f:
    columns = line.split(",")
    letters = columns[ 0 ]
    list1 += [ letters ]

also I am not sure why you put columns[ 1 ], I thought you wanted the first element, which is columns[ 0 ] :)

yeah sorry...never mind the [1]...my mistake...thank you for your help...much appreciated...

0

The more common approach would be to use append() ...

for line in f:
    columns = line.split(",")
    letters = columns[ 0 ]
    list1.append(letters)

I think it is less mistake prone. I also want to point out, that should you want to read the second column (the end of each line), you will find a newline character attached.

Since you title is File to dictionary this may become important.

Edited by vegaseat: newline

0

To make it short with python list comprehensions.
Not that this make code better or more readable in many cases.
But think this line is not so bad to understand.

>>> f = [line[0] for line in open('ab.txt')]
>>> f
['a', 'c', 'e', 'g']
>>>

Read every characters.
So colum 2 will be line[2]

Edited by snippsat: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.