Search code examples
pythonlisttuplespython-itertools

How should I break a list of tuples so that it forms lists with same keys?


I have

iList = [('FirstParam', 1), ('FirstParam', 2), 
         ('FirstParam', 3), ('FirstParam', 4), 
         ('SecondParam', 5), ('SecondParam', 6), 
         ('SecondParam', 7)]

I am trying to form:

iList1 = [('FirstParam', 1), ('FirstParam', 2), 
         ('FirstParam', 3), ('FirstParam', 4)]

iList2 = [('SecondParam', 5), ('SecondParam', 6), 
         ('SecondParam', 7)]

I tried:

for key, group in itertools.groupby(iList, operator.itemgetter(0)):
    print "List",(list(group))

it prints 2 lists the wayI wanted. Output:

List [('FirstParam', 1), ('FirstParam', 2), 
         ('FirstParam', 3), ('FirstParam', 4)]
List [('SecondParam', 5), ('SecondParam', 6), 
         ('SecondParam', 7)]

My concern is how should i make those as iList1 and iList2? I don't get the way (list(group)) works and prints the list.


Solution

  • You can use a list comprehension and unpack into iList1 and iList2:

    iList1, iList2 = [list(group) for key, group in itertools.groupby(iList, operator.itemgetter(0))]
    

    Then you will get what you want:

    >>> iList1
    [('FirstParam', 1), ('FirstParam', 2), ('FirstParam', 3), ('FirstParam', 4)]
    >>> iList2
    [('SecondParam', 5), ('SecondParam', 6), ('SecondParam', 7)]