[Tutor] sorting lists into sub lists based on a key

Kent Johnson kent37 at tds.net
Thu Jun 21 02:46:42 CEST 2007

Iyer wrote:
> if I have a list of lists, that goes like this: 
> [[0,['a','b']],[0,['c','d']],[3,['f','g']], [0,['a','b']],[0,['c','d']], 
> [3,['f1','f2']], [2,['zz','dd']]]
> what could be the best way to reorder this such that the sublists with 
> the same first element go into their own sub-list ?
> Does this seem to be the best way to do it ?
> list1 = []
> for key, items in groupby(data_list, key= itemgetter(0)):    
>     list1.append(list(items))

This looks good to me. You could use a list comprehension which is a bit 
more concise and idiomatic:
list1 = [ list(items) for key, items in groupby(data_list, key= 
itemgetter(0)) ]

I can't help thinking that perhaps you should be using dicts to hold 
your data, you seem to have key/value pairs, but without knowing more 
about the problem I can't tell.


More information about the Tutor mailing list