def GroupBy(items, key):
 key_map = {}
 try:
  item_iter = iter(items)
 except TypeError:
  item_iter = [items]
 for item in item_iter:
  key_id = key(item)
  key_map.setdefault(key_id, []).append(item)
 return key_map

def GroupBy ( items , key ) : key_map = { } try : item_iter = iter ( items ) except TypeError : item_iter = [ items ] for item in item_iter : key_id = key ( item ) key_map . setdefault ( key_id , [ ] ) . append ( item ) return key_map
a generator that groups all items by a key .