0

I've stumbled upon a problem I just can't seem to find an answer for. I am reading the contents of a csv file using csv.DictReader and constructing a list of namedtuples from that information. However, upon running it, the end result is an empty list.

from collections import namedtuple
import csv

nt = namedtuple('suminfo', 'a, b, c')
checklist = ['check1', 'check2', 'check3']

with open('test.csv', 'r') as csv_file:
     csv_rows = csv.DictReader(csv_file, delimiter='\t')
     tups = [nt(row['first'], row['second'], row['third']) 
            for row in csv_rows if row['first'] in checklist]

I have also tried a typical normal loop of the rows followed by list appending of a namedtuple, and this seems to work just fine.

Why is the listcomprehension not behaving as expected? Thank you for your time.

Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
Jenez
  • 29
  • 8

1 Answers1

2

The list comprehension is working for me. I used this test data (test.csv):

first   second  third
check1  1   1
check2  2   2
check3  3   3
check4  4   4

The values are separated by tabs. When I run your code,

nt = namedtuple('suminfo', 'a, b, c')
checklist = ['check1', 'check2', 'check3']

with open('test.csv', 'r') as csv_file:
    csv_rows = csv.DictReader(csv_file, delimiter='\t')
    tups = [nt(row['first'], row['second'], row['third']) 
            for row in csv_rows if row['first'] in checklist]
    print(tups)

I get the following result:

>>> [suminfo(a='check1', b='1', c='1'), suminfo(a='check2', b='2', c='2'), suminfo(a='check3', b='3', c='3')]
Hayley Guillou
  • 3,953
  • 4
  • 24
  • 34
  • 1
    10 bucks says the OP's file is not tab delimited. – Jared Smith Apr 20 '17 at 17:02
  • @JaredSmith Sorry to dissapoint but the error seems to have been somewhere else. I just copied my own code and ran in stand-alone and it did what I was expected. Seems to be a silly spelling mistake somewhere. – Jenez Apr 21 '17 at 08:33
  • 1
    Thanks for taking your time to verify that it works! – Jenez Apr 21 '17 at 08:34