1

I have a function, table(), that reads a csv file and returns the rows in individual lists. I want to map these lists to create a dictionary, with field headers being the keys and the underlying rows being the values. I cannot seem to do this however. When I try to call only the first element within the list of lists I created from the function ( l) in the command prompt, it returns all the lists up to 'N', the first letter in the word 'None', despite me breaking (return) if reader is None. When I do the same with a sys.stdout to a text file, it does the same, but the 'N' is replaced with <type 'list'>. Does anyone know what I'm doing wrong, and how I can go about creating a dictionary (or a list of columns, for that matter) from a CSV file given my table() function?

import csv

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row
        if reader is None:
            return

l = list(str(table()))
keys = l[0]
print keys

Output text file:

['Field1', 'Field2', 'Field3', 'Field4']
['a', '1', 'I', 'access']
['b', '2', 'II', 'accessing\n']
['c', '3', 'III', 'accommodation']
['d', '4', 'IIII', 'basically']
<type 'list'>

2 Answers 2

3

More pythonically

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            yield row
2
  • I wish they'd backport yield from. I'm down with a from __future__ import yield statement.
    – jdotjdot
    Dec 7, 2012 at 15:36
  • @jdotjdot It's a lovely feature. I really miss it when I'm not in 3.3. Dec 7, 2012 at 15:45
1

You don't actually return anything from the table function. Try it like this:

def table():
    with open('C:\\Python27\\test.csv', 'rb') as f:
        lines = []
        reader = csv.reader(f)
        if reader:
            for row in reader:
                lines.append(row)
            return lines
        else:
            return []
2
  • Excellent. Thank you both. The strangest thing appears, however, when I attempt to create a dictionary of columns from the table. The headers are assigned as keys, and the table contents as values, just like I would expect. However, the headers match to the rows (Header 1 matches Row 1) instead of matching to the columns like I would expect.
    – baobobs
    Dec 7, 2012 at 16:10
  • The following solution helped: l = table() keys = l[0] value = l[1:] values = zip(*value) dictionary = dict(zip(keys, values)) print dictionary
    – baobobs
    Dec 7, 2012 at 16:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.