def sorted_groupby(seq, key):
 if (not hasattr(key, '__call__')):
  key = operator.attrgetter(key)
 return itertools.groupby(sorted(seq, key=key), key=key)

def sorted_groupby ( seq , key ) : if ( not hasattr ( key , '__call__' ) ) : key = operator . attrgetter ( key ) return itertools . groupby ( sorted ( seq , key = key ) , key = key )
given a sequence .