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.

Recommended Answers

All 6 Replies

Member Avatar for masterofpuppets

Hint:

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

:)

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?

Member Avatar for masterofpuppets

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 ] :)

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...

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.

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]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.