def groupby(key, seq):
 if (not callable(key)):
  key = getter(key)
 d = collections.defaultdict((lambda : [].append))
 for item in seq:
  d[key(item)](item)
 rv = {}
 for (k, v) in iteritems(d):
  rv[k] = v.__self__
 return rv

def groupby ( key , seq ) : if ( not callable ( key ) ) : key = getter ( key ) d = collections . defaultdict ( ( lambda : [ ] . append ) ) for item in seq : d [ key ( item ) ] ( item ) rv = { } for ( k , v ) in iteritems ( d ) : rv [ k ] = v . __self__ return rv
group a collection by a key function .