Need more efficient way to parse out csv file in Python
Question: Here's a sample csv file

    
    
    id, serial_no
    2, 500
    2, 501
    2, 502
    3, 600
    3, 601
    

This is the output I'm looking for (list of serial_no withing a list of ids):

    
    
    [2, [500,501,502]]
    [3, [600, 601]]
    

I have implemented my solution but it's too much code and I'm sure there are
better solutions out there. Still learning Python and I don't know all the
tricks yet.

    
    
    file = 'test.csv'
    
    data = csv.reader(open(file))
    fields = data.next()
    
    for row in data:
      each_row = []     
        each_row.append(row[0])
        each_row.append(row[1])
        zipped_data.append(each_row)
    for rec in zipped_data:
      if rec[0] not in ids:
        ids.append(rec[0])
    for id in ids:
        for rec in zipped_data:
          if rec[0] == id:
            ser_no.append(rec[1])
      tmp.append(id)
      tmp.append(ser_no)
      print tmp
      tmp = []
      ser_no = []
    

**I've omitted var initializing for simplicity of code

    
    
    print tmp
    

Gives me output I mentioned above. I know there's a better way to do this or
pythonic way to do it. It's just too messy! Any suggestions would be great!


Answer: 
    from collections import defaultdict
    
    records = defaultdict(list)
    
    file = 'test.csv'
    
    data = csv.reader(open(file))
    fields = data.next()
    
    for row in data:
        records[row[0]].append(row[1])
    
    #sorting by ids since keys don't maintain order
    results = sorted(records.items(), key=lambda x: x[0])
    print results
    

If the list of serial_nos need to be unique just replace `defaultdict(list)`
with `defaultdict(set)` and `records[row[0]].append(row[1])` with
`records[row[0]].add(row[1])`

