Concatenate Values into Strings for Each Group

Question

I have a text file like this:

key1 value1 A

 

key1 value2 B

 

key1 value3 A

 

key2 value1 A

 

key2 value2 B

 

I am trying to open it as a dictionary and print the list of keys and values separated by commas so it looks like this in the end:

 

key1 value1,value2,value A,B,A

 

key2 value1,value2,value A,B

 

I am trying the following code:

 

f = open('file.txt', 'r')

 

answer = {}

 

for line in f:

 

list = ",".join(map(str,f))

 

 print list

 

But it's not working.

 

Answer

It’s a simple SQL-like computation that we group records and then concatenate field values together. It’s complicated to achieve it in Python. But it’s a piece of cake if you handle it in SPL (Structured Process Language):

 

A

1

=file("file.txt").import()

2

=A1.group(_1;~.(_2).concat@c(),~.(_3).concat@c())

A2: Group records by _1 and then respectively concatenate values in _2 and those in _3 by commas.

undefined

esProc provides JDBC interface to let a third-party program to call an SPL script in the way they call a database result set. To know more about the invocation, see How to Call an SPL Script in Java.