def group_by(items, key_fn):
 groups = defaultdict(list)
 for item in items:
  key = key_fn(item)
  groups[key].append(item)
 return groups

def group_by ( items , key_fn ) : groups = defaultdict ( list ) for item in items : key = key_fn ( item ) groups [ key ] . append ( item ) return groups
returns a defaultdict .