What the following code does is:
The key field is column0 (where sometimes there could be single key, and sometimes keys separated by comma).
The rest of the columns are also either single or comma separated. But based on the single key value from column0, the goal is to collect all the values as a set in the rest of the columns.
import sys
import csv
dict={}
def getVal(k):
try:
v = dict[k]
except:
v= None
return v
# First read as a line and first transformation separates first column
# and stores into a table with key,value (where value is the remaining)
for line in sys.stdin:
line = line.strip()
row = line.split('\t')
l = len(row)
keyvalues = row[0]
items = keyvalues.split(",")
for item in items:
key = item
value=[]
for i in range(1, l):
value.append(row[i].split(","))
if getVal(key) == None:
dict[key] = value
else:
prevval = dict[key]
cols = len(prevval)
newvalue=[]
newlist = []
for j in range(0,cols):
newlist = prevval[j]+value[j]
newset = set(newlist)
newvalue.append(list(newset))
dict[key] = newvalue
for k,v in dict.items():
rowstr = k+"\t"
ncols = len(v)
for items in v:
cols=""
for item in items:
cols +=item+","
cols = cols[0:len(cols)-1]
rowstr += cols+"\t"
print rowstr
Sample input
3,15,75 1635,1762 878 3425 121,122,123
15 1762 871 3475 121,125,126
3 1585,1590,5192 882,832,841 3200,3211 120,121,122,123,124
I'm getting the results correctly as expected, but I would like to know any improvements to make on the code.