Skip to content Skip to sidebar Skip to footer

Splitting A List Into Two Lists Based On A Unique Value

I have a text file that looks something like this: hello 12 hello 56 world 25 world 26 Is there a way in python that I can somehow parse the list that I obtain from reading this d

Solution 1:

Use a dict and group by the first column:

from csv import  reader
from collections import defaultdict
withopen("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

withopen("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']]

Solution 2:

Since you don't seem to be sure what data structure would be appropriate to store the result, let me suggest an ordered dictionary mapping the keywords in the first column to a list of the integer values (in order of their appearance):

>>>from collections import OrderedDict>>>result = OrderedDict()>>>withopen('input.txt') as f:...for line in f:...        key, val = line.split()...        result.setdefault(key, []).append(int(val))...>>>result
OrderedDict([('hello', [12, 56]), ('world', [25, 26]))

Solution 3:

loop this:

dict={}
#start the loop here
x=readdatafromfile.split()

if x[0] notindict.keys():
    dict[x[0]] = list()
dict[x[0]].append(x[1])

#end loop hereprintdict.keys() #for first columnprintdict['hello'] #for list of values of hello

Post a Comment for "Splitting A List Into Two Lists Based On A Unique Value"