[Solved] splitting a list into two lists based on a unique value


Use a dict and group by the first column:

from csv import  reader
from collections import defaultdict
with open("in.txt") as f:
    d = defaultdict(list)
    for k, v in reader(f,delimiter=" "):
        d[k].append(v)

print(d.values())

Which will give you all the values in two separate lists:

[['25', '26'], ['12', '56']

If the data is always in two sections you can use a groupby:

from itertools import groupby
from csv import  reader
from operator import itemgetter

with open("in.txt") as f:
    print([list(map(itemgetter(1), v)) 
           for k, v in groupby(reader(f,delimiter=" "), key=itemgetter(0))])

Which will give the same output:

 [['12', '56'], ['25', '26']]

2

solved splitting a list into two lists based on a unique value