-3

I have a csv file with a list like this:

12, 1233, 234

12, 1233, 989

12, 9898, 213

14, 1233, 987

14, 1233, 876

I want to make an array for the rows which are similar. for example in the above example, i want make an array of which is like this: 12, 1233 [234, 989] since the values in their first two rows are same

import csv with open('check.csv', 'r') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',') for row in reader:
         print(re.search( #uniqueSet = list(set(x)) 
Merlin
  • 24,552
  • 41
  • 131
  • 206
vins
  • 27
  • 1
  • 2
  • 12

1 Answers1

0

This code will do most of the work for you

#read the csv file
with open('csv_file.csv','r') as f:
   lines=[l.split(',') for l in f.readlines()]
#Aggregate by the 3rd field by the first two fields
import collections    
d=collections.defaultdict(list)
for l in lines:
   d[(l[0],l[1])].append(l[2])

The csv (csv_file.csv) file would be read as a dictionary (variable d), all you have left is to transform it to a list or whatever format you want

Uri Goren
  • 13,386
  • 6
  • 58
  • 110
  • import csv import collections with open('file.csv','r') as f: #lines=[l.split(',') for l in f.readlines()] reader = [l.split(',') for l in f.readlines()] d=collections.defaultdict(list) for l in reader: d[l[0]+':'+l[1]].append(l[2]) uniqueSet = list(set(l)) print(d) this works! – vins May 27 '16 at 19:38
  • If my answer was helpful please accept it or at least vote up – Uri Goren May 27 '16 at 19:48
  • 2
    Hi yes! i accepted it , but i am unable to vote it up since i need 15 points to vote.. :) – vins May 27 '16 at 20:31